bash history

~ 2 min read

If your using the command line a lot, then being able to quickly search and recall past commands from the bash history becomes a great way to make your life easier and more productive.

Interactive search of bash history

Type Ctrl R at the command line and start typing something that will match the previous command. Once a relevant match appears, you can either keep hitting Ctrl R to search backwards again in the history or continue typing until you get to the right command. When the command you want finally appears, simply press Enter to place into the command line, or to cancel press ESC.

Less interactive ways of searching the history

Bash keeps a history which you can print out with the history command.

$ history
1 ls -al
2 vi ~/.ssh/config
3 ssh somehost
4 history
$

There’s a few ways to interact with the history using commands starting with a ! (also know as a splat or bang)

Simplest of all to recall and execute the command at position one type

!1

you can substitute any number of the history to get another command. You can also recall previous commands with relative numbers so

!-2

Would recall and run the ssh command in the history. !! and !-1 are the same and mean run the last command.

!ls

Recalls the first command searching backwards that starts ls and runs it.

!?somehost

Recalls the most recent command containing somehost and runs it.

^string1^string2^

Repeat the last command replacing string1 with string2.

One last thing so, all this recall and run is great, but what if you want to recall and eyeball the command before it runs? Feels safer right? Then set this option in your shell.

shopt -s histverify

And commands will not auto run, but simply replace the current command line, so you can eyeball, and modify or press Enter to run.

all posts →