Linux下history命令

在 Linux 下,history 默认会把命令记录在 当前 shell 会话用户的历史文件(通常是 ~/.bash_history~/.zsh_history)中。如果你只想清除 特定命令 而不是全部历史。


1.查看历史命令编号

1
history

输出类似:

 1001  ls -l
 1002  cd /var/log
 1003  rm -rf /tmp/test
 1004  history

每条命令前面都有一个编号。


2.删除指定编号的命令

比如你要删除 rm -rf /tmp/test(编号 1003):

1
history -d 1003

这会从 当前 shell 会话历史 中删除。

注意:编号可能因新执行命令而变化,最好先 history 再删除。


3.保存修改到历史文件

Bash 会在 shell 退出时把会话历史写入 ~/.bash_history,如果希望立即更新文件:

1
history -w
  • -w:写入历史文件
  • -r:从文件重新读取历史(reload)

4.删除包含特定字符串的历史命令(批量)

假设要删除所有含 rm -rf 的命令:

1
2
3
4
5
6
# 用 sed 删除历史文件中的特定行
sed -i '/rm -rf/d' ~/.bash_history

# 再从当前会话重新读取
history -c
history -r
  • history -c:清空当前会话历史
  • history -r:重新加载文件到会话

5.临时不记录历史命令

1
2
3
4
5
# 临时不记录
HISTIGNORE='rm -rf *' # 忽略所有 rm -rf 命令

# 或者当前命令不记录
command_to_run # 前面加空格(bash 默认 HISTCONTROL=ignoreboth 时)

💡 总结

  • history -d <编号> 删除单条
  • sed -i '/pattern/d' ~/.bash_history 批量删除
  • history -w 保存到文件