Ubuntu – How to search previous terminal commands like on a Mac? (alt. to CTRL+R)

command linekeyboard

I have a Mac laptop for work, and while on the terminal (on iterm2), I can start typing a command (e.g. ssh) then press "up" key to browse through my recent commands that begin with whatever I started typing (e.g ssh …….).

On Ubuntu terminal, I can see a similar feature with the keyboard shortcut "CTRL + R". However, it's not quite the same. Is there a way to mimic the Mac feature?

Thank you!

Edit with examples for clarity:

Here's an example of what I mean on the Mac.
Let's say in the past 100 commands run in my Mac terminal, I had 2 commands that were:

ssh 1.2.3.4
ssh 127.0.0.1

Then when I type "ssh" and hit "up" key, it would autofill to ssh 127.0.0.1, and if I hit "up" key again, it would fill to ssh 1.2.3.4.

However, on Ubuntu terminal, if let's say my 3 most recent commands were

ssh 1.2.3.4 
open .
echo "help me"

Then by typing "ssh" and hitting "up" key, it would simply take me to echo "help me". And hitting "up" key again would take me to open .

To me it makes more intuitive sense to have this pattern instead of having to use the CTRL+R route.

Best Answer

Open the $HOME/.inputrc file in a text editor (e.g. gedit ~/.inputrc) and add these two lines:

"\e[A": history-search-backward
"\e[B": history-search-forward

Now, save and close the file and open a new terminal. You know how pressing the up arrow key cycles through the command history? Now with these lines, if you start typing and then press the up arrow key, only commands that started with what you've typed will be shown. Typing ping and then pressing the up arrow key again will show the next to last ping command, and it goes back to the preceding ping command each time you press the up arrow key again. This makes it very easy to find the specific commands you were after.

Example

  1. Type sudo.

    sudo
    
  2. Press the up arrow key to autocomplete sudo to the last command that started with sudo.

    sudo apt update && sudo apt upgrade
    
  3. Please note that for commands that start with sudo you will be asked to authenticate with your user password as usual before the command can be executed.