How to Search Past Terminal Commands in Linux


One of the single-handedly, most useful tools I use in terminal is one that allows me to search past terminal commands.

We all know that we can select the up and down arrow keys to navigate our past terminal commands incrementally.

What if we have a long command that we’ve previously run and want to run again? We don’t have to aggressively “up” our way to that command.

The history Command

You may know that running history in your terminal will list all the previous commands you’ve executed.

You can obtain the same results by searching through ~/.bash_history.

...
503  python script1.py
504  ssh user@192.168.1.27
505  ls ~
506  find . -type f
507  history

We can search this list using reverse-i-search, or Ctrl+R.

The Ctrl+R Command

reverse-i-search searches “backwards starting at the current line and moving up through the history as necessary.” (Source).

When you press Ctrl+R, you’ll see this prompt:

(reverse-i-search)`':

If we want to re-run python script1.py, we can type script1, and the reverse-i-search will return the most recent searching containing script1. It doesn’t necessarily have to start with it.

(reverse-i-search)`script1': python script1.py

We can cycle through all the options by continuously pressing Ctrl+R.

Useful Tip 1: Comment Your Commands

You may have a command that you frequently use, but don’t want to navigate through all of those commands in reverse-i-search.

reverse-i-search will actually match against comments as well, so try this:

python script1.py # first

And then run the search.

(reverse-i-search)`first': python script1.py # first

Useful Tip 2: Extend history Length

By default, many operation systems set the default history size to small values (e.g. Ubuntu: 1000).

We can extend the length of our history search by setting these values inside ~/.bashrc and ~/.bash_profile.

HISTFILESIZE=1000000000
HISTSIZE=1000000

Useful Tip 3: Run Previous Command with !!

Suppose we ran a command and forgot to run it with sudo.

We can use !! to execute the previous command, then add sudo to it.

sudo !!

Useful Tip 4: Reference Previous Arguments with !$

Let’s say we made a mistake and wrote car (not a real command) instead of cat (a real command).

car ~/.bashrc

This will produce an error, so we need to rewrite the command.

Instead of pressing the up arrow and scrolling left to the command itself, we can use !$ to reference ~/.bashrc.

cat !$