When you are managing a Linux server, you will frequently type incredibly long, complex commands containing multiple flags and directory paths (e.g., rsync -avz --exclude 'logs' /var/www/ user@backup:/mnt/storage/). If you need to run that exact same massive command again five minutes later, manually retyping it is tedious and invites catastrophic typos. Instead, you can use the built-in history command to instantly retrieve and execute your past actions.
What is the History Command?
Every time you press Enter in the bash terminal, Linux quietly saves the exact text of your command into a hidden text file (usually named .bash_history). The history command is a tool that reads this file and prints your past actions to the screen, assigning a unique ID number to each one.
How to View Your History
- Open your Linux terminal.
- Type the following simple command:
history
- Press Enter.
The terminal will instantly output a numbered list of the last 500 or 1,000 commands you have executed. For example:
401 cd /var/www/html
402 nano index.php
403 systemctl restart apache2
404 rsync -avz /var/www/ user@backup:/mnt/storage/
How to Re-run a Command Using its ID Number
If you want to instantly execute command number 404 again, you do not need to copy and paste the text. You can use the “bang” (!) symbol followed immediately by the ID number.
Type the following and press Enter:
!404
Linux will instantly pull the exact text from history line 404, print it to the screen for confirmation, and immediately execute it.
The Double-Bang Shortcut
The most common scenario in Linux is typing a long command, pressing Enter, and immediately receiving a “Permission Denied” error because you forgot to type sudo at the beginning.
Instead of pressing the “Up” arrow and manually typing sudo, you can use the “double-bang” (!!) shortcut, which mathematically represents “the very last command you executed.”
Simply type:
sudo !!
Press Enter. Linux will instantly grab your previous failed command, append sudo to the front of it, and execute it flawlessly.