【问题标题】:bashs's command behavior about exit pipe exit. `exit 1 | exit 2`bashs 关于出口管道出口的命令行为。 `退出1 |出口 2`
【发布时间】:2021-09-15 06:57:28
【问题描述】:

我很好奇bash的行为和输入命令时的退出状态

exit [exit status] | exit [exit status] | .. [repetition of exit and exit status]

它给了我下面的输出。并且,然后不退出。

这是未定义的行为吗?

bash-3.2$ exit 1 | exit 2
bash-3.2$ echo $? 
2

【问题讨论】:

  • 您可以使用PIPESTATUS 数组检查管道中每个命令的退出状态。

标签: bash exit


【解决方案1】:

来自bash man page

管道中的每个命令都作为单独的进程执行(即,在子外壳中)。

因此,即使是第一个 exit 也不会退出您的 shell,因为它只会退出子 shell。

关于退出代码:

管道的返回状态是最后一个命令的退出状态,除非启用了 pipefail 选项。如果启用了 pipefail,则管道的返回状态是最后一个(最右边)以非零状态退出的命令的值,如果所有命令都成功退出,则返回零。

您可以像这样激活pipefail

$ set -o pipefail
$ exit 1 | exit 2 | exit 0
$ echo $?
2

【讨论】:

    【解决方案2】:

    exit 1 | exit 2 不是顺序的,而是并发的。

    即使最后一个命令从第一个命令获取 STDOUT 输出。 What is a simple explanation for how pipes work in Bash?

    此外,这些命令中的每一个都在一个子shell中执行。 因此,您键入命令的主 shell 不会退出。

    管道命令就像一个完整的命令组合,而不是一个接一个的命令。

    如果你想退出,你可以让它连续exit 1 || exit 2

    最后,默认情况下,$? 是最近的前台管道退出状态。 What are the special dollar sign shell variables?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2021-05-31
      • 1970-01-01
      相关资源
      最近更新 更多