Search⌘ K
AI Features

Bash History

Explore Bash's command history features to re-run and modify previous commands effortlessly. Understand key shortcuts, environment variables controlling history, and dynamic history searching to improve your command line efficiency. Learn practical tips for mastering history usage and customization in your Bash environment.

How Important is this Lesson?

Bash’s history features are used at the command line so often that it’s difficult to understate how important they are. It’s a rich subject, but here I keep to the features I use most of the time.

Bash and History

Bash keeps a history of commands you have run. It keeps this in memory.

Shell
history
Terminal 1
Terminal
Loading...

Using Your History

It can be tedious to type out often-used commands and arguments again and again, so bash offers several ways to save your effort.

Type this out and try and figure out what is going on:

Shell
echo nowhere
cd !$ # !$ is replaced by 'nowhere', the last argument to the previous command
echo 'About bash history' > file1
echo 'Another file' > file2
grep About file1
!! # Repeat the last command
grep About file2
grep Another !$
rm file2
!e # Repeat the last command beginning with 'e'
!gr # Repeat the last command beginning with 'gr'

That introduced a few tricks you haven’t necessarily seen before.

All of them start with the ! (or so-called bang) sign, which is the sign used to indicate that the bash history is being referred to.

  • The simplest, and most frequently seen is the double bang !!, which just means: re-run the previous command

  • The one I use most often, though, is the second one you come across in the listing above: !$, or bang dollar. This one I must use dozens of times every day. It tells bash to re-use the last argument of the previous command.

  • Finally, a bang followed by ‘normal’ characters re-runs the last command that matches those starting letters. The !e looks up the last command that ran starting with an e and runs that. Similarly, the !gr runs the last command that started with a gr, ie the grep.

Notice that the command that’s rerun is the evaluated command. For that grep, what is re-run is as though you typed: grep Another file2, and not: ...