How to Use History Command in Linux: Syntax and Examples
Use the
history command in Linux to display a list of previously executed commands in your terminal. You can run history alone to see all past commands or use options like history N to show the last N commands.Syntax
The basic syntax of the history command is simple and flexible:
history: Shows all past commands with line numbers.history N: Shows the last N commands.!number: Re-executes the command with the given history number.!string: Re-executes the most recent command starting withstring.
bash
history [N] !number !string
Example
This example shows how to list the last 5 commands and then rerun a specific command by its history number.
bash
history 5 !3
Output
1 ls
2 pwd
3 echo "Hello World"
4 date
5 whoami
Hello World
Common Pitfalls
Common mistakes include:
- Trying to use
!numberwithout checking the correct command number first, which can run unintended commands. - Assuming
historyshows commands from all sessions; it only shows the current session's history unless saved. - Not knowing that history commands are stored in a file (usually
~/.bash_history) and may requirehistory -wto save manually.
bash
echo "Hello" !10 # May run wrong command if 10 is not what you expect # Correct way: history 10 # Check commands first !10 # Then run
Quick Reference
| Command | Description |
|---|---|
| history | Show all commands in current session |
| history N | Show last N commands |
| !number | Run command by its history number |
| !string | Run last command starting with string |
| history -c | Clear the history list |
| history -w | Write current session history to file |
Key Takeaways
Use
history to view your past commands in the terminal.Run a previous command quickly with
!number or !string.Always check the command number with
history before re-executing to avoid mistakes.History is session-based and saved to a file; use
history -w to save manually.Clear your history with
history -c if needed for privacy.