为什么从 Bash 历史记录中删除条目时会出现错误?

opt*_*lic 8 bash command-history xargs

我的 Bash 历史记录中有一些我想删除的命令。

我可以找到它们history | grep "command with password"然后删除它们history -d <line-number>

但是,当我尝试通过管道将它们批量删除时,xargs我收到一个错误:

history | grep "command with password" | awk '{print $1}' | sort -r | xargs history -d
xargs: history: No such file or directory
Run Code Online (Sandbox Code Playgroud)

我认为这xargs会遍历行号列表并将其一一发送给history -d命令。

是什么导致了这个错误?

注意:我知道还有其他方法可以删除历史记录,问题纯粹是为了提高我对xargs工作原理以及导致错误的错误的理解。

Qua*_*odo 13

引发错误是因为 xargs 找不到history命令。它是一个内置的 shell,你可以用 确认type history,因此 xargs 不可见。尝试

echo 1 | xargs history -d; echo $?
Run Code Online (Sandbox Code Playgroud)

返回值为 127。 在man xargs, EXIT STATUS 部分

echo 1 | xargs history -d; echo $?
Run Code Online (Sandbox Code Playgroud)

扩展ilkkachu 的评论,原则上您可以调用 Bash 并history从生成的外壳调用。

echo 1 | xargs -I {} bash -c 'echo $HISTFILE; history' bash {}
Run Code Online (Sandbox Code Playgroud)

history在 Bash shell 可以使用所有内置命令之后,上述命令不会引发错误。但是,从同一个命令中还发现HISTFILE未设置并且不history输出任何内容:在非交互式 shell 上未启用历史记录。同样,您可以使用set内置、导出HISTFILEHISTFILESIZE……来激活它……但我们不想让您头疼。直接编辑.bash_history是最直接的方法。

  • @opticyclic,它_可能_,如果它使用 shell 来启动程序,而不是自己做。无论如何,您都可以使用`xargs sh -c 'some shell code' sh` 之类的东西来完成。它只是不会_帮助_,因为该 shell 副本可能与您启动整个管道的主 shell 具有不同的历史概念 (6认同)
  • @opticyclic 一开始有点令人惊讶,但如果你仔细想想,xargs 将如何决定寻找哪个 shell 来寻找内置函数?`bash`、`ksh​​`、`dash`、`zsh`?它没有走那么远似乎是合理的。 (5认同)