🎓 A1Learner
🔍
0 of 50 lessons completed

Shell History

Shell history is the list of commands you have typed before. The history command shows the list, and you can run an old command again from it.

Read a fixed history file

HISTFILE names the history file. history -r reads it, and history prints it.

printf 'ls notes.txt\ncat notes.txt\nwc -l notes.txt\n' > myhist
HISTFILE=myhist
history -r
history

Repeat a command by number

!2 runs the command on line 2 of the history list.

!2

Repeat the last command

!! runs the last command again. It saves retyping a long command.

!!

Example

printf 'cat notes.txt\nsort notes.txt\nwc -l notes.txt\n' > myhist
HISTFILE=myhist
history -r
history

Key points

  • History: the list of commands you have typed before.
  • Use history to show the list with line numbers.
  • Use !n to run the command on line n of the list.
  • Use !! to run the last command again.
  • HISTFILE: the file where the shell saves the history.

In this example, three commands are written to a history file. history -r reads the file, and history prints the three lines with numbers.

Note

History expansion with ! works in an interactive shell, not inside a script.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does !! do?