从 shell 管道返回 true

Returning true from a shell pipeline

我想根据另一个命令的 return 值有条件地执行 gnu makefile 中的命令。

具体来说,是这样的:

lsmod | grep -q pfc && sudo rmmod pfc

如果 lsmod 输出的当前模块列表包含 pfc,请将其删除。这是有效的,有一个小问题,如果 grep 命令失败(模块不存在)整个管道 returns 非零,这会导致命令被解释为失败,但实际上这是成功了。

我可以在末尾添加一个 ; true 以始终强制它成功,但这不会捕获 rmmod 命令中的失败!

我想要一些主要可移植到 sh 实现中的东西,但从技术上讲,我想我正在使用 dash,因为那是 sh 指向 Ubuntu 的地方。

您可以通过使用像 echo -n:

这样的 nop 命令清除退出值来处理预期的失败
if lsmod | grep -q pfc; then sudo rmmod pfc; else echo -n; fi

如果缺少输出,则执行 nop 命令并整行 returns 和 $?=0

编辑:
建议的更简单的 nop 看起来像:

if lsmod | grep -q pfc; then sudo rmmod pfc; else true; fi

响应

if lsmod | grep -q pfc; then sudo rmmod pfc; else :; fi