...

/

Bash History

Bash History

This lesson gives you a pragmatic overview of bash’s history features, which can save you lots of time when at the terminal. You will learn about where your history is stored, how previous commands can be referenced, and various options and variables that can be set when working with your shell history.

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.

Press + to interact
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:

Press + to interact
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 ...