Complete Guide to the Linux history Command

Linux 命令大全Linux Command Encyclopedia

history is an extremely useful built-in command in Linux systems. It records all the command history that users have executed in the terminal. This feature is especially valuable in the following scenarios:

  1. Trace operations: View previously executed commands
  2. Quick reuse: No need to retype long commands
  3. Troubleshooting: Check system operation records
  4. Efficiency improvement: Quickly complete repetitive tasks using historical commands

When you enter commands in the terminal, Bash saves them in memory and writes them to~/.bash_historythe file (under default configuration).


Basic Syntax and Usage

The basic syntax of the history command is very simple:

history [选项] [参数]

Common Forms

1. View the complete history:

history

2. View the most recent N records:

history 10  # 显示最近10条命令

3. Clear all history:

history -c

4. Delete a specific history record (e.g., delete entry 1010):

history -d 1010

Detailed Explanation of Common Options and Parameters

The history command supports several useful options:

Option Description Example
-c Clear all history history -c
-d Delete the history record at the specified position history -d 1005
-a Immediately write history from memory to the history file history -a
-n Read unread history records from the history file history -n
-r Read the contents of the history file into the current session history -r
-w Write the current history to the history file history -w

Practical Tips and Advanced Usage

1. Quickly Execute Historical Commands

Example

!n        # Execute the nth command in history
!!        # Execute the previous command
!string   # Execute the most recent command starting with string

Example:

Example

!1024     # Execute the command numbered 1024 in history
!!        # Re-execute the previous command
!vim      # Execute the most recent command starting with vim

2. Search Historical Commands

UsingCtrl+Ryou can reverse search history commands; enter a partial keyword to find the matching command.

3. Historical Command Substitution

Example

^old^new  # Replace old with new in the previous command and execute

Example:

Example

$ cat file1.txt
$ ^file1^file2  # Equivalent to executing cat file2.txt

4. Display Command Timestamps

In~/.bashrcAdd the following configuration to display command execution time:

Example

export HISTTIMEFORMAT="%F %T "

Then execute:

Example

source ~/.bashrc

After thathistorythe command will display the execution time of each command.


Environment Variable Configuration

The behavior of the history command can be customized through environment variables:

Variable Description Recommended Value
HISTSIZE Number of history commands kept in memory 5000
HISTFILESIZE Number of commands kept in the history file 10000
HISTCONTROL Controls the way history is recorded ignoredups:erasedups
HISTIGNORE Specifies commands not to record "ls:cd:pwd:exit"

Configuration example (add to~/.bashrc):

Example

export HISTSIZE=5000
export HISTFILESIZE=10000
export HISTCONTROL=ignoredups:erasedups
export HISTIGNORE="ls:cd:pwd:exit"
export HISTTIMEFORMAT="%F %T "

Practical Application Scenarios

Scenario 1: Recover Forgotten Commands

Example

history | grep "apt install"

Scenario 2: Count the Most Frequently Used Commands

Example

history | awk '{CMD[$2]++;count++;} END {for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10

Scenario 3: Back Up History Records

Example

history -a  # Ensure the latest commands have been written to the file
cp ~/.bash_history ~/command_history_backup_$(date +%F).txt

Notes

  1. Privacy and security: Historical records may contain sensitive information (e.g., passwords); protect them accordingly
  2. Multiple terminal issue: Different terminal sessions do not share history in real time by default
  3. History loss: Abnormal exit may cause commands not to be saved
  4. Large file handling: Excessively large history files may affect performance

Summary and Exercises

  1. Review your command history and find the 5 most recently used git commands

    history | grep git | tail -5
  2. Configure your bash environment so that history records include timestamps and ignore duplicate commands

  3. Create an alias to quickly back up the current history to a specified directory

    alias backup_history='cp ~/.bash_history ~/history_backups/history_$(date +%Y%m%d_%H%M%S).txt'
  4. Try usingCtrl+Rto search for a complex command you have used before.

By mastering the history command, you can significantly improve your efficiency in the Linux terminal, reduce redundant input, and better manage your command-line operation history.

Linux 命令大全Linux Command Encyclopedia

Other Extensions