本文介绍了为什么bash不会因短路命令序列中的错误而因错误而停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行带有 -e 选项的bash脚本时,看到的一些行为对我来说是没有意义的,该脚本具有多个与&& s,其中之一失败.我希望脚本在失败的命令上停止并返回退出状态,但它只会愉快地执行脚本的其余部分.

I'm seeing some behavior that doesn't make sense to me when I run a bash script with the -e option that has multiple commands strung together with &&s and one of them fails. I would expect the script to stop on the failed command and return the exit status, but instead it just executes the rest of the script happily.

以下是对我有意义的示例:

Here are examples that make sense to me:

$ false && true; echo $?
1

$ bash -xe -c "false && true"; echo $?
+ false
1

$ bash -xe -c "false; true"; echo $?
+ false
1

这对我来说是没有意义的:

And here is the one that does not make sense to me:

$ bash -xe -c "false && true; true"; echo $?
+ false
+ true
0

这是我不知道发生了什么的地方. false&&true 返回状态1,因此脚本不应停止执行并返回状态1,就像脚本为 false时一样.是?

This is where I don't understand what is going on. false && true returns status 1 so shouldn't the script stop executing and return status 1, like it does when the script is false; true?

在进行实验时,我发现它能像我期望的那样用括号括住命令链:

While experimenting, I found that it works the way I would expect if I surround the chain of commands with parentheses:

$ bash -xe -c "(false && true); true"; echo $?
+ false
1

有人可以对此进行解释吗?

Can anybody give an explanation for this?

推荐答案

此处的逻辑是您对&& 的使用已经 进行了错误检查.即使使用 set -e ,bash也不会将 if 条件内的失败视为值得中止的方式.

The logic here is that your use of && already is error-checking. The same way bash doesn't treat a failure within an if condition as worth aborting, even with set -e.

将命令包装在括号中时,实际上是在子shell中运行这些命令,因此脚本本身只能看到该子shell的返回,即:它不知道&&完全参与其中,因此它会按您的预期中止.

When you wrap the commands in a parenthesis, you are actually running those commands within a subshell, so the script itself only sees the return of that subshell, ie: it isn't aware that && is involved at all, so it aborts as you expect.

这篇关于为什么bash不会因短路命令序列中的错误而因错误而停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:54