bash - make -e 只从子shell退出

标签 bash shell subshell

#!/bin/bash -eu

items="1 2"
for item in $items; do
(
    echo one
    false
    echo two
) ||:
done

我希望 false 行中断子 shell,但继续处理外循环。 IE。预期输出是

one
one

但是,我明白了

one
two
one
two

就好像 ||: 恰好位于 false 行之后,而不是子 shell 之后。

谁能解释一下,为什么会发生这种情况?

最佳答案

在子 shell 内设置 -e 并删除 ||::

#!/bin/bash -u

items="1 2"
for item in $items; do
(
    set -e
    echo one
    false
    echo two
)
done

另一种看似有效的方法是:

#!/bin/bash -eu

items="1 2"
for item in $items; do
(
    echo one
    false
    echo two
) | awk '{print}'
done

我认为您的方法不起作用的原因如下(引自man bash):

The shell does not exit if the command that fails is [...] part of any command executed in a && or || list except the command following the final && or ||

关于bash - make -e 只从子shell退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16586060/

相关文章:

bash - 重定向文本时缩进代码

python - 从 Applescript 调用 Python 脚本

linux - 在 bash 中迭代管道中的文件名

python - 无法在 django shell python 中导入 readline

bash - 为什么要避免子外壳?

r - 从 R 中调用 bash

python - 使用python生成petsc二进制文件

python - 从 Python3 代码中运行 bash 脚本的问题

正则表达式(或 bash),获取引号之间的管道(perl)

linux - python将shell的输入截断为特定数字