“set -e"是怎么来的?使用子外壳? [英] How does "set -e" work with subshells?
问题描述
我想知道 set -e
是否通过子 shell 传播(即子 shell 是否继承了其父级的 -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
现在我尝试在我的子shell中放置一个子shell会发生什么.此表达式返回 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 )
为什么?在这两种情况下,无论 set -e
是否传播,内部子 shell 都返回 1(正如我在开始时检查的那样).外层子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 如果管道(可能由单个简单命令组成)、子shell com-括在括号中的命令,或作为括起的命令列表的一部分执行的命令之一by 大括号(参见上面的 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.
这篇关于“set -e"是怎么来的?使用子外壳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!