Chuniversiteit logomarkChuniversiteit.nl
Living the Pipe Dream

How to find previously used terminal commands in Linux and macOS

Unix shells remember which commands you have issued through them. Here are a few ways to make use of that command history.

Jack Shephard tells us we have to go back into our shell history
We have to go back, Kate!

One line at a time

Link

Almost everyone already knows this one, but I’m mentioning it anyway for the sake of completeness: you can easily look up previously entered commands by pressing the Up button (⬆︎) until you’ve found what you’re looking for.

If it’s been a while since you last executed that command, it may take a lot of key presses before you get there though…

All the history

Link

The history command lists all commands that have been issued by the user that’s currently logged in. This is mainly handy in situations where you want to see an overview of commands.

By sending the output of the history command to grep using a pipe operator (|) we can filter the history so that it only shows commands that contain specific words. For example, to show all previously used commands that include the string “git config” you would run history | grep 'git config':

Don’t forget to add quotes to your search string if it contains spaces; otherwise grep will try to treat each subsequent keyword as a file or directory name:

GOTO history

Link

Most people who use the history | grep method manually copy and paste the command that they want to execute again, but there’s actually no need for this. You may have noticed that each line of history’s output is .

Entering !, followed by the number of the command that you were looking for, and pressing Enter will write the contents of that line to the terminal:

sudo make me a sandwich

Link

There’s another shortcut, !!, which you can use to quickly reissue the last command. This is especially useful when you forgot to prepend sudo to your command:

Instead of manually retrieving and modifying the last command, simply use !!, which serves as a placeholder for the contents of the original command:

Link

The final method to look up previously issued commands is the method that I use most often: interactive search.

Press to enable interactive search mode. You can now look up commands by entering a search string, e.g. git push (no need to add quotes).

If you’ve found the command you want, press Enter to execute it. Otherwise, keep typing to improve your query, press Ctrl+R to view the next result, or press Ctrl+C to exit interactive search mode.

Interactive search mode can be a huge time saver, so make sure you use it often!