gpt4 book ai didi

shell - 如何导致 Linux 管道失败?

转载 作者:行者123 更新时间:2023-12-04 03:01:00 26 4
gpt4 key购买 nike

最近在学习set -e Ubuntu 14.04 上的 POSIX shell。我的引用资料是“IEEE Std 1003.1-2008, 2016 Edition”的“Shell & Utilities”一章。来自 this section我看到-e当命令在管道中失败时,不会导致脚本退出(除非失败的命令是管道中的最后一个):

The failure of any individual command in a multi-command pipeline shall not cause the shell to exit. Only the failure of the pipeline itself shall be considered.



然后我写了一个简单的脚本来确认这个行为:
(
set -e
false | true | false | true
echo ">> Multi-command pipeline: Last command succeeded."
)
(
set -e
false | true | false
echo ">> Multi-command pipeline: Last command failed."
)

打印出“上次命令成功”消息,而不会打印出“上次命令失败”消息。

我的问题是:
  • 链式命令 false | true | false似乎不是管道的故障。这只是最后一个命令的失败。 管道本身仍然成功。我对吗??
  • 有没有办法模拟管道故障? 我们可以使用 false模拟命令失败。管道是否有类似的命令?
  • 最佳答案

    默认情况下,在 bash 中,管道的成功或失败完全由管道中的最后一个命令决定。

    但是,您可以启用 pipefail选项( set -o pipefail ),如果管道中的任何命令失败,管道将返回失败。

    例子

    此管道成功:

    $ false | true | false | true ; echo $?
    0

    此管道失败:
    $ set -o pipefail
    $ false | true | false | true ; echo $?
    1

    文档

    来自 man bash :

    The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.

    关于shell - 如何导致 Linux 管道失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49267554/

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