gpt4 book ai didi

bash - 为什么 bash errexit 在函数调用中的行为不符合预期?

转载 作者:行者123 更新时间:2023-11-29 08:52:22 32 4
gpt4 key购买 nike

在 bash 手册页中,它指出:

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 并为该子 shell 启用了 errexit,也会执行命令列表中的所有命令。这是一个演示问题的简单示例:

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

现在,如果我对它们中的每一个应用一个条件...

( 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

最佳答案

您开始引用 manual但随后你删掉了解释这种行为的部分,它在紧接着的一句话中:

-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 - 为什么 bash errexit 在函数调用中的行为不符合预期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19789102/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com