bash 在函数内部发生错误时中止吗?

问题描述 投票:0回答:1

请注意:

mark@L-R910LPKW:~$ f(){ set -euo pipefail ; git statu; echo $?; } && f && echo OK ; set +euo pipefail
git: 'statu' is not a git command. See 'git --help'.

The most similar commands are
        status
        stage
        stash
1
OK
mark@L-R910LPKW:~$

命令是

f(){ set -euo pipefail ; git statu; echo $?; } && f && echo OK ; set +euo pipefail

我的问题是 - 为什么函数

f
NOT 在运行失败后立即中止
git statu
?运行该命令清楚地显示
git statu
失败,退出代码为 1,但仍进一步继续到
echo $?
,而不是按照
set -e
的要求中止。

bash
1个回答
0
投票

这在手册中有详细记录:

[当设置

-e
时,如果失败的命令是紧随
while
until
关键字的命令列表的一部分(
if
语句中的测试的一部分),则 shell 不会退出,
&&
||
列表中执行的任何命令的一部分,最后一个
&&
||
之后的命令除外,管道中除最后一个命令之外的任何命令,或者如果命令的返回状态与
! 反转
.

如果复合命令或 shell 函数在忽略

-e
的上下文中执行时设置
-e
,则在复合命令或包含函数调用的命令完成之前,该设置不会产生任何效果。

您的函数确实在不忽略

-e
的上下文中中止。例如:

$ f(){ set -euo pipefail ; git statu; echo $?; }
$ ( f; echo OK )
git: 'statu' is not a git command. See 'git --help'.

The most similar commands are
        status
        stage
        stash
$
© www.soinside.com 2019 - 2024. All rights reserved.