Get previous commands in Terminal that match the currently typed command [duplicate]
Emily Wong
In some terminals you can do something like this...
Type some command
nmap -sn 192.168.1.1/24Then go on to do other things in the terminal for a while. Then later you can type
nmapand then just press the ↑ key and it will index through all of the commands that started with what you typed, in this case nmap for example.
My example was pretty short but sometimes you type a very long command that you want to run again, and I know you can press ↑ until you find it again, but that goes through every command and could take a while if you typed it long ago.
Is there anyway to get this to work in Ubuntu's Terminal?
34 Answers
Yes, there is a very simple way to search through your command history. When at the terminal, press Ctrl-R to begin a search, then you can type nmap and it will search back to the last command using nmap.
If you don't want the last command that contained the 'nmap' word but some other further to the past, then you can hit Ctrl-R again as many times as you'd like.
I always use history it's just more convinient for me to see all the commands that I type for example:
historylists you all commands that you typed for a while
history | grep nmaplists you only commands with nmap
history | grep nmap | tail -10
history | grep nmap | head -10lists you last and first 10 commands with nmap
then just copy and paste it again.
2The way that I prefer to use to achieve this is by re-maping the Up and Down keys to Bash's history search. This can be achieved by adding the following to .inputrc:
"\e[A": history-search-backward
"\e[B": history-search-forwardAfter reloading your shell, pressing Up or Down on an empty prompt will navigate through all of the commands, and pressing Up or Down after typing e.g. nmap will navigate through all of the commands that started with what you typed.
If you are in vi mode in bash (set -o vi), you can go in command mode (press Esc), and then type /whatever_you_want, followed by Enter.
It will search whatever you want, and you can scroll with j and k keys. Hit enter when you found the right command.
To be able to type commands when you have hitted Esc, you have to hit i (this is vi).
Going back to "normal" shell mode is done via set -o emacs.