๐Ÿ“˜ Mastering the Terminal: The Bash History

Understanding and efficiently using Bash history helps speed up workflow, avoid retyping, and even prevent mistakes.


๐Ÿ“‚ Where is Bash History Stored?

  • History is saved in: ~/.bash_history

  • Two environment variables control its behavior:

    Variable

    Description

    Example

    HISTFILESIZE

    Max number of commands in the .bash_history file

    echo $HISTFILESIZE โ†’ 2000

    HISTSIZE

    Max number of commands kept in memory (used by history command)

    echo $HISTSIZE โ†’ 1000

โš ๏ธ .bash_history is only updated after logout.


๐Ÿ“œ Viewing History

history            # Show recent commands (from memory, not full file)
cat ~/.bash_history  # Show saved command history from the file

๐Ÿš€ Rerunning Commands

Syntax

Action

!number

Run the command by its history number (e.g., !17)

!!

Run the last command

!-n

Run the command that was n commands ago (e.g., !-3)

!command

Run the most recent command that starts with command (e.g., !ping)

!command:p

Print the matched command without executing it


๐Ÿ” Navigating History

Shortcut

Action

โ†‘ / Ctrl + P

Previous command

โ†“ / Ctrl + N

Next command

Ctrl + R

Reverse search in history (interactive)

Ctrl + G

Exit reverse search without executing

Ctrl + P in reverse search

Run the found command

โœ… Example:

Ctrl + R โ†’ type 'ping' โ†’ press Enter โ†’ runs last 'ping' command
Ctrl + R โ†’ type 'cat' โ†’ Ctrl + G โ†’ exits search mode

๐Ÿงน Cleaning History

Command

Action

history -d <number>

Delete a specific command by its number

history -c

Clear the entire session history


Updated on