在Linux中,Bash Shell提供了一个名为history的命令,用于显示用户最近执行过(guo)的(de)命令历史记录,这个命令非常有用,特别是当你需要快速回顾或重现(xian)之前的命令操作时,本文将详细介绍如何在Linux中使用Bash history命令。
1. 查看历史命令列表


要查看历史命令列表,只(zhi)需(xu)在终端中输入以下命令:

history
这将(jiang)显示一个包含所有已执行命令的列表,每(mei)个命令前面(mian)都有一个(ge)数字,表示它在历史记录中的位置。
1 ls 2 cd /home/user 3 pwd 4 sudo apt-get update 5 sudo apt-get upgrade
2. 清空历史命令记录
如果你想清空历史(shi)命令记录,可以使用以下(xia)命令:
history -c
这将删除所(suo)有保存的历史命令,请注意,这不(bu)会影(ying)响当前正在(zai)执行的命令。
3. 导出历史命令到文件
如果你想将历史命令导出到一个(ge)文件中,可以使用以(yi)下命令:
history > history.txt
这将把所有历史命令保存到名(ming)为history.txt的文件中,你可(ke)以使用文本编辑器打开这(zhe)个文件来查看或编辑命令,要恢复这些(xie)命令,只需再次(ci)运行(xing)上面的命令即可。
4. 使用上下箭头键浏览历史(shi)命令
在显示历史命令列表时,你可(ke)以使用上(shang)下箭头键在列表中导航,上箭头键将显示更早的历史命令,而(er)下(xia)箭头键将显示更晚的历史(shi)命令,这样,你可以(yi)快速找到并执行之前执行过的任何命令。
5. 使用HISTTIMEFORMAT环境变量设置时间戳格式
默认情况下,Bash history命令显示(shi)的命令后面会带有时间戳,表示该命令最后一次被执行的时间(jian),你可以通过设置HISTTIMEFORMAT环境变量来自定义时间戳的格式,要将时间戳格式更改为"YYYY-MM-DD HH:MM:SS",可以执行以下命令:
export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S"
然后再次运(yun)行history命令,你将看到带有自定义时间戳格式的(de)命令列表,要使这(zhe)些更改永久生效,请将上(shang)述export命令添加到你的~/.bashrc或~/.bash_profile文件中。
Q1: 如(ru)何查看Bash history中的(de)第N个(ge)命令?
答:要查看Bash history中(zhong)的第N个命令,可以使用以下命令(其中N是你想要查看的命令位置):
history | tail -n +N | head -n 1 | xargs -I { } bash -i -c "{ }"Q2: 如何删除某个特定(ding)目录下的所有历史命令?
答:要删除某个特定目录下(xia)的所有历史(shi)命令,可以使用以下脚本:
!/bin/bashDIR="/path/to/your/directory"find "$DIR" -type f -name "*.sh" | while read file; do echo "$file"; done | xargs grep -l "history" | cut -d ' ' -f1 | xargs sed 's/(!]*)! history ([^!]*)/1rm 2/' | sh && find "$DIR" -type f -name "*.sh" | while read file; do echo "$file"; done | xargs grep -l "rm" | cut -d ' ' -f1 | xargs sed 's/(!]*)rm ([^!]*)/1history 2/' | sh && find "$DIR" -type f -name "*.sh" | while read file; do echo "$file"; done | xargs grep -l "history" | cut -d ' ' -f1 | xargs bash --login --norc --noprofile --rcfile=~/.bashrc --init-file=~/.bash_profile --exec bash -< $file && clear && find "$DIR" -type f -name "*.sh" | while read file; do echo "$file"; done | xargs grep -l "rm" | cut -d ' ' -f1 | xargs sed 's/(!]*)rm ([^!]*)/1history 2/' | sh && find "$DIR" -type f -name "*.sh" | while read file; do echo "$file"; done | xargs grep -l "history" | cut -d ' ' -f1 | xargs bash --login --norc --noprofile --rcfile=~/.bashrc --init-file=~/.bash_profile --exec bash -< $file && clear && find "$DIR" -type f -name "*.sh" | while read file; do echo "$file"; done | xargs grep -l "history" | cut -d ' ' -f1 | xargs bash --login --norc --noprofile --rcfile=~/.bashrc --init-file=~/.bash_profile --exec bash -< $file && clear && find "$DIR" -type f -name "*.sh" | while read file; do echo "$file"; done | xargs grep -l "history" | cut -d ' ' -f1 | xargs bash --login --norc --noprofile --rcfile=~/.bashrc --init-file=~/.bash_profile --exec bash -< $file && clear && find "$DIR" -type f -name "*.sh" | while read file; do echo "$file"; done | xargs grep