gpt4 book ai didi

bash - 如何在错误时中断 bash 管道?

转载 作者:行者123 更新时间:2023-11-29 09:14:54 26 4
gpt4 key购买 nike

在下面的示例中,无论管道中先前命令的退出代码如何,都会执行 echo 语句:

asemenov@cpp-01-ubuntu:~$ 
asemenov@cpp-01-ubuntu:~$ false|echo 123
123
asemenov@cpp-01-ubuntu:~$ true|echo 123
123
asemenov@cpp-01-ubuntu:~$

我希望 echo 命令仅在上一个命令的 退出代码上执行,也就是说我想实现此行为:

asemenov@cpp-01-ubuntu:~$ false|echo 123
asemenov@cpp-01-ubuntu:~$

在 bash 中可以吗?

这是一个更实际的例子:

asemenov@cpp-01-ubuntu:~$ find SomeNotExistingDir|xargs ls -1
find: `SomeNotExistingDir': No such file or directory
..
..
files list from my current directory
..
..
asemenov@cpp-01-ubuntu:~$

如果 find 失败,则没有理由执行 xargs ls -1

最佳答案

管道的组件总是无条件地、逻辑地并行运行;仅当第一个(或更早的)过程成功完成时,您才能在管道中进行第二个(或之后的)过程。

在使用 find 显示的特定情况下,您至少有两个选择:

find SomeNotExistingDir ... -exec ls -1 {} +

或者您可以使用 GNU xargs 的一个非常有用的功能(POSIX 中没有):

find SomeNotExistingDir ... | xargs -r ls -1

-r 选项等同于 --no-run-if-empty 选项,它相当准确地解释了它的作用。如果您使用 GNU find 和 GNU xargs,您应该使用扩展名 -print0-0:

find SomeNotExistingDir ... -print0 | xargs -r -0 ls -1

这会正确处理可以出现在文件名中的每个字符。

关于bash - 如何在错误时中断 bash 管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13797095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com