为什么bash errexit在函数调用中表现不正常? [英] Why is bash errexit not behaving as expected in function calls?

查看:183
本文介绍了为什么bash errexit在函数调用中表现不正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash手册页中指出:

In the bash man page, it states:

如果管道(可能由一个简单的命令组成)立即退出,
用括号括起来的subshel​​l命令,或者执行为 用大括号括起来的命令列表的一部分...

Exit immediately if a pipeline (which may consist of a single simple command),
a subshell command enclosed in parentheses, or one of the commands executed as part of a command list enclosed by braces...

因此,我认为应该将函数视为用大括号括起来的命令列表.但是,如果对函数调用应用条件,则errexit不再持久存在于函数主体中,并且在返回之前它会执行整个命令列表.即使您在该函数内为该子Shell启用了errexit的情况下显式创建了一个子shell,该命令列表中的所有命令也会被执行.这是一个演示该问题的简单示例:

So I assumed that a function should be considered a command list enclosed by braces. However, if you apply a conditional to the function call, errexit no longer persists inside the function body and it executes the entire command list before returning. Even if you explicitly create a subshell inside the function with errexit enabled for that subshell, all commands in the command list are executed. Here is a simple example that demonstrates the issue:

function a() { b ; c ; d ; e ; }
function ap() { { b ; c ; d ; e ; } ; }
function as() { ( set -e ; b ; c ; d ; e ) ; }
function b() { false ; }
function c() { false ; }
function d() { false ; }
function e() { false ; }


( set -Eex ; a )
+ a
+ b
+ false


( set -Eex ; ap )
+ ap
+ b
+ false


( set -Eex ; as )
+ as
+ set -e
+ b
+ false

现在,如果我对每个对象都应用条件...

Now if I apply a conditional to each of them...

( set -Eex ; a || false )
+ a
+ b
+ false
+ c
+ false
+ d
+ false
+ e
+ false
+ false


( set -Eex ; ap || false )
+ ap
+ b
+ false
+ c
+ false
+ d
+ false
+ e
+ false
+ false


( set -Eex ; as )
+ as
+ set -e
+ b
+ false
+ c
+ false
+ d
+ false
+ e
+ false
+ false

推荐答案

您开始引用

You started to quote the manual but then you cut the bit that explained this behaviour, which was in the very next sentence:

-e如果可能由单个简单命令,用括号括起来的subshel​​l命令或作为用括号括起来的命令列表一部分执行的命令之一的管道返回非零状态,则立即退出. 如果失败的命令是紧随whileuntil关键字之后的命令列表的一部分,则外壳不会退出,这是if语句中测试的一部分, part在&&||列表中执行的任何命令的最后一个&&|| 之后的命令,管道中除最后一个命令之外的任何命令,或者该命令的返回状态正在反转的命令中的命令与!.

-e Exit immediately if a pipeline, which may consist of a single simple command, a subshell command enclosed in parentheses, or one of the commands executed as part of a command list enclosed by braces returns a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command’s return status is being inverted with !.

这篇关于为什么bash errexit在函数调用中表现不正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆