如何从 shell 终端历史记录 (zsh) 中删除未知命令

时间:2021-02-05 00:17:28

标签: shell terminal zsh zshrc

我正在尝试在 zsh 中设置我的历史记录。我已经激活了像 HIST_IGNORE_ALL_DUPS 这样的选项,它会删除历史记录中的重复命令。

但我也在寻找一些可以删除不存在的命令的选项,这些命令返回 127“未找到命令”。

1 个答案:

答案 0 :(得分:2)

Zsh 中没有这样的选项,但这可以通过 zsh-hist plugin 轻松实现:

autoload -Uz add-zsh-hook

command-not-found () {
  # -f: force
  # -s: silent
  # d: delete
  # -1: most recent history item
  (( ? == 127 )) && hist -fs d -1
}

add-zsh-hook precmd command-not-found

如果返回 127,这将自动从历史记录中删除最后一项。

或者,除了删除它,您还可以将已删除的命令加载到编辑缓冲区中,这样您就可以立即修复您所犯的任何错字,使用 hist f 而不是 hist d

autoload -Uz add-zsh-hook

command-not-found () {
  # f: fix
  (( ? == 127 )) && hist -fs f -1
}

add-zsh-hook precmd command-not-found