zsh 函数仅包装 grep 输出 returns 几行

zsh function wrapping grep output only returns a few lines

我正在尝试创建一个小的 zsh 函数,它允许我 grep 我的历史记录 - hgrep test 应该 return 我输入的每个命令都包含 test.

在我的机器上它只有 return 大约 6 个结果。当我输入 history | grep test 时,我得到了 很多 个结果。什么给了?

hgrep (){
     history | grep 
}

输出 - 这是完整的!

➜  ~ hgrep test
 7887  mkd test
 7889  rm -r test
 7894  hgrep test
 7896  history | grep test

这是不完整的输出。另外,请注意第一个结果

➜  ~ history | grep test
  252  cp mgroup /test
  254  cp mgroup /test
  322  vi test.js
  324  node test.js
  325  vi test.js
...

经过一番摸索,行为差异似乎与 .zshrc 的来源有关。在新终端上,我看到了不需要的行为。如果我然后 source ~/.zshrc 它有效。

但是,我仍然很困惑为什么会这样。

命令的作用完全不同。

 history | grep test

列出所有包含字符串test的历史事件。

history test

返回历史记录中以字符串 test 开头的最近命令,并列出所有后续命令。

您的 history 命令似乎在定义 hgrep 函数后被 alias 编辑为其他内容(例如 fc -l 1)。

因此,您可以将 hgrep 函数定义放在 alias 设置之后。 或者,您可以定义不受别名、shell 选项等影响的 hgrep 函数(以及任何函数)

TL;DR

命令 history 默认列出最后 16 个事件。

history

same as fc -l.
[…]
fc -l ... [ first [ last ] ]

If first is not specified, it will be set to -1 (the most recent event), or to -16 if the -l flag is given.

-- zshbuiltins(1) Shell Builtin Commands fc, history

并在读取时检查和扩展别名。

Every eligible word in the shell input is checked to see if there is an alias defined for it. If so, it is replaced by the text of the alias if it is in command position
[…]
aliases are expanded when the code is read in; the entire line is read in one go

-- zshmisc(1) Aliasing

hgrep 函数似乎使用了 shell-内置命令 history,它只显示了几个事件,结果可能与使用 history(它是一个 alias 到别的东西)交互。

hgrep函数将被source ~/.zshrc重新定义,此时该函数中的history将expanded/replaced变为alias。 您可以通过发出以下命令来检查生成的函数:

% functions hgrep
hgrep () {
…
(hgrep function's definition will be shown)