history 是 Linux shell 中用于显示和管理命令历史记录的内置命令。它可以帮助用户快速查找和重复执行之前的命令。
基本语法
常用选项
| 选项 |
说明 |
-c |
清空历史记录 |
-d OFFSET |
删除指定偏移量的历史记录 |
-a |
追加当前会话的历史记录到历史文件 |
-n |
读取未读的历史记录 |
-r |
读取历史文件并追加到历史列表 |
-w |
将当前历史记录写入历史文件 |
-p |
展开历史参数但不执行 |
-s |
将参数作为单个条目添加到历史列表 |
基本使用
显示历史记录
1 2 3 4 5 6 7 8
| ➜ history
➜ history 20
➜ history 10
|
使用历史记录
1 2 3 4 5 6 7 8 9 10 11
| ➜ !N
➜ !!
➜ !pattern
➜ !pattern
|
搜索历史记录
1 2 3 4 5
| ➜ history | grep pattern
|
历史记录扩展
基本扩展
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| ➜ !!
➜ !123
➜ !-1 ➜ !-2
➜ !ls
➜ !?pattern?
|
参数扩展
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| ➜ ls file1 file2 ➜ cat !^
➜ ls file1 file2 ➜ cat !$
➜ ls file1 file2 ➜ cat !*
➜ ls file1 file2 file3 ➜ cat !:2
|
命令部分扩展
1 2 3 4 5 6 7
| ➜ /usr/bin/ls -l ➜ !:0
|
历史记录配置
环境变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| export HISTSIZE=10000
export HISTFILESIZE=20000
export HISTFILE=~/.bash_history
export PROMPT_COMMAND="history -a"
export HISTCONTROL=ignoredups
export HISTCONTROL=ignorespace
export HISTCONTROL=ignoreboth:erasedups
|
配置文件
在 ~/.bashrc 或 ~/.bash_profile 中配置:
1 2 3 4 5 6 7 8 9 10 11 12
| HISTSIZE=10000 HISTFILESIZE=20000
HISTCONTROL=ignoredups:erasedups
PROMPT_COMMAND="history -a; history -c; history -r"
HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S "
|
实际应用场景
查找命令
1 2 3 4 5
| ➜ history | grep "nginx"
➜ history | tail -20
|
重复执行
修改并执行
1 2 3 4 5 6 7
|
➜ ^ls^cat
➜ ls file1.txt ➜ cat !$
|
清空历史
1 2 3 4 5 6
| ➜ history -c
➜ > ~/.bash_history ➜ history -w
|
高级用法
历史记录搜索
历史记录共享
1 2 3
|
export PROMPT_COMMAND="history -a; history -c; history -r"
|
历史记录统计
1 2 3 4 5
| ➜ history | awk '{print $2}' | sort | uniq -c | sort -rn | head -10
➜ history | awk '{print $2}' | sort | uniq -c | sort -rn
|
注意事项
- 历史文件位置:默认在
~/.bash_history(bash)或 ~/.zsh_history(zsh)
- 历史记录数量:默认保存有限数量的历史记录
- 安全性:历史记录可能包含敏感信息(密码等),注意保护
- 不同 shell:不同 shell(bash、zsh)的历史记录机制略有不同
参考文献