为什么我的 zsh 历史记录中有重复项?

xen*_*ide 15 command-history zsh

> zsh --version
zsh 5.7.1 (x86_64-apple-darwin19.0)
Run Code Online (Sandbox Code Playgroud)
> setopt
alwaystoend
autocd
autopushd
combiningchars
completeinword
correct
extendedhistory
noflowcontrol
histexpiredupsfirst
histignorealldups
histignorespace
histreduceblanks
histsavenodups
histverify
interactive
interactivecomments
login
longlistjobs
monitor
promptsubst
pushdignoredups
pushdminus
sharehistory
shinstdin
zle
> cat ~/.zsh_history
: 1595363811:0;ls 2&>1 /dev/null
: 1595363821:0;ls /dev/null
: 1595363831:0;cat ~/.zsh_history
: 1595363837:0;ls /dev/null
: 1595363841:0;setopt
: 1595363845:0;cat ~/.zsh_history
: 1595363993:0;setopt
: 1595364000:0;ls
: 1595364009:0;cat ~/.zsh_history
Run Code Online (Sandbox Code Playgroud)

如果它们是一个接一个的,那么它就会忽略它们histignoredups,但据我所知,我的配置应该忽略任何一个和全部。

> zsh --version
zsh 5.7.1 (x86_64-apple-darwin19.0)
Run Code Online (Sandbox Code Playgroud)

第二个问题:我应该选择~/.zshrc还是~/.zshenv

VVK*_*VVK 21

将以下行添加到您的~/.zshrc文件中以避免历史记录中出现重复

setopt HIST_EXPIRE_DUPS_FIRST
setopt HIST_IGNORE_DUPS
setopt HIST_IGNORE_ALL_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_FIND_NO_DUPS
setopt HIST_SAVE_NO_DUPS
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用!更具体地说:使用 `nano ~/.zshrc` 编辑配置文件;然后我只需要添加“setopt HIST_IGNORE_ALL_DUPS”,最后添加“source ~/.zhrc”来应用更改 (8认同)

小智 13

修剪所有重复项所需的唯一选项是histignorealldups,并且您已经设置了它,所以是的,正在删除重复项

凭记忆

您正在查看存储在文件 ( cat $HISTFILE) 中的历史记录。

如何重现

启动一个新的 zsh 实例,删除所有历史记录并执行一些命令

% zsh -i
% a=( $(setopt) )
% unsetopt $a
% HISTSIZE=0
% HISTSIZE=99
% history
   95  HISTSIZE=99
% setopt INC_APPEND_HISTORY
% ls >/dev/null
% clear
% ls >/dev/null
% history
  113  HISTSIZE=99
  114  history
  115  setopt INC_APPEND_HISTORY
  116  ls >/dev/null
  117  clear
  118  ls >/dev/null
Run Code Online (Sandbox Code Playgroud)

现在,您可以设置该选项histignorealldups,所有重复项都会消失(从内存中):

% setopt histignorealldups
% history
  113  HISTSIZE=99
  115  setopt INC_APPEND_HISTORY
  117  clear
  118  ls >/dev/null
  122  setopt histignorealldups
Run Code Online (Sandbox Code Playgroud)

但这并不意味着这些行已从历史文件中删除:

% cat ~/.histfile | tail -n 10
setopt INC_APPEND_HISTORY
ls >/dev/null
clear
ls >/dev/null
history
setopt histignorealldups
history
setopt histignorealldups
history
cat ~/.histfile | tail -n 10
Run Code Online (Sandbox Code Playgroud)

要从文件中删除重复项,您必须编辑该文件。

我建议您不要这样做,因为历史记录可能由多个并行运行的 zsh 实例共享。这不是一个小问题。

  • 是的,您可以通过设置“HIST_SAVE_NO_DUPS”。只需确保将“HISTSIZE”设置为比“SAVEHIST”更大的值即可。否则,就行不通。 (2认同)