如何“设置”与subshells一起工作? [英] How does "set -e" work with subshells?
问题描述
我想知道是否 set -e
通过subshells传播(即,subshell是否继承 -e
它的父母),所以我做了一些实验。我发现一些奇怪的结果,我无法解释。
I was wondering whether set -e
propagates through subshells (i.e. does a subshell inherit the -e
setting of its parent), so I made some experiments. I found some strange results that I can't explain.
首先,这里有一些基本的测试。他们返回我的期望。
First, here are some basic tests. They return what I expect.
( true; false ) # 1
( false; true ) # 0
( set -e; false; true ) # 1
现在我尝试了如果我把在我的子壳内的一个子壳。此表达式返回1,这表示它传播。
Now I tried what happens if I put a subshell within my subshell. This expression returns 1, which suggests that it propagates.
( set -e; ( false; true ) )
然后我尝试了这些表达式。我希望他们返回1,但是我发现他们返回0。
Then I tried these expressions. I expected them to return 1, but I found that they return 0.
( set -e; ( true; false ); true )
( set -e; ( set -e; false; true ); true )
为什么呢?在这两种情况下,内部子shell返回1,无论 set -e
是否传播(正如我在开始检查)。外部子shell具有 set -e
,这意味着内部子shell退出后应该失败,但不会。有人可以解释一下吗?
Why? In both cases, the inner subshell returns 1, whether set -e
propagates or not (as I checked in the beginning). The outer subshell has set -e
, which means that it should fail after the inner subshell exits, but it does not. Can someone explain this?
推荐答案
在 bash之前
4, set -e
似乎只会导致shell退出,如果一个简单的命令有一个非零退出(强调我的):
Prior to bash
4, set -e
appears to only cause the shell to exit if a simple command has a non-zero exit (emphasis mine):
-e如果简单命令(参见上面的SHELL GRAMMAR)退出,则立即退出。
-e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status.
在 bash
4(可能4.1,我没有4.0检查), -e
被扩展到更复杂的命令:
In bash
4 (possibly 4.1, I don't have a 4.0 to check), the effect of -e
was extended to more complicated commands:
-e如果管道(可能包含单个简单命令),一个包含在括号中的subshell
命令,或者作为命令列表的一部分执行的命令列表中的一个命令列表(通过上面的SHELL GRAMMAR)(包括上面的SHELL GRAMMAR)退出,零状态。
-e Exit immediately if a pipeline (which may consist of a single simple command), a subshell com- mand enclosed in parentheses, or one of the commands executed as part of a command list enclosed by braces (see SHELL GRAMMAR above) exits with a non-zero status.
这篇关于如何“设置”与subshells一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!