0
0
Linux-cliHow-ToBeginner · 3 min read

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 with string.
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 !number without checking the correct command number first, which can run unintended commands.
  • Assuming history shows 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 require history -w to 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

CommandDescription
historyShow all commands in current session
history NShow last N commands
!numberRun command by its history number
!stringRun last command starting with string
history -cClear the history list
history -wWrite 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.