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.
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
... 503 python script1.py 504 ssh firstname.lastname@example.org 505 ls ~ 506 find . -type f 507 history
We can search this list using
reverse-i-search searches “backwards starting at the current line and moving up through the history as necessary.” (Source).
When you press
R, you’ll see this prompt:
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
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 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
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
Useful Tip 3: Run Previous Command with
Suppose we ran a command and forgot to run it with
We can use
!! to execute the previous command, then add
sudo to it.
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).
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