The Linux terminal is a powerful tool, but it requires typing long, complex, and highly specific commands. If you spent twenty minutes yesterday piecing together a massive rsync command to back up your web server, and you need to run it again today, you do not need to memorize it or search the internet to recreate it. The bash shell records every single command you type. To view this record, you use the history command.
The Basics of the history Command
The history command is built directly into the bash shell. It requires no installation.
Simply open your terminal and type:
history
Press Enter. Your terminal will instantly print a numbered list of the last 500 to 1,000 commands you have executed on that machine, in chronological order, with the most recent command at the very bottom.
How to Search Your History
If your history list contains 1,000 entries, scrolling through it manually to find a specific tar command from three weeks ago is incredibly tedious. You can combine history with the grep command to instantly filter the results.
To find every command in your history that included the word “tar”, type:
history | grep "tar"
The terminal will filter out the noise and only print the lines containing your search term, making it trivial to find the exact syntax you used.
How to Instantly Re-run a Past Command
The primary reason you use the history command is to avoid retyping complex strings. When you run history, you will notice every command has a number next to it (e.g., 452 sudo apt update).
If you want to instantly execute command number 452 again, you use the exclamation point (known as a “bang” in Linux) followed immediately by the number, with no spaces.
!452
Press Enter. Linux will instantly recall that exact command, print it to the screen, and execute it.
The Double Bang Trick: The most common use case for history shortcuts is the double bang (!!). If you type a long command, hit enter, and get a “Permission denied” error because you forgot to add sudo, you do not need to retype the command. Simply type:
sudo !!
The !! tells Linux “take the very last command I just ran and insert it here.” The terminal will execute the command with superuser privileges, saving you time and frustration.