我们最近有一次关于bash的经历,即使我们找到了一个解决方案,它仍然在扭曲我的想法. bash如何评估&&表达式的返回码?
执行此脚本,因为myrandomcommand不存在而失败:
#!/bin/bash set -e echo "foo" myrandomcommand echo "bar"
结果是预期的一个:
~ > bash foo.sh foo foo.sh: line 6: myrandomcommand: command not found [exited with 127] ~ > echo $? 127
但是使用&&&&表达:
#!/bin/bash set -e echo "foo" myrandomcommand && ls echo "bar"
ls语句未执行(因为第一个语句失败并且不评估第二个语句),但脚本的行为非常不同:
~ > bash foo.sh foo foo.sh: line 6: myrandomcommand: command not found bar # ('bar' is printed now) ~ > echo $? 0
我们发现使用括号(myrandomcommand&& ls)之间的表达式,它按预期工作(如第一个例子),但我想知道原因.
你可以在bash的手册页中阅读:
原文链接:https://www.f2er.com/bash/385075.html-e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with 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 a && or || list,or if the command's return value is being inverted via !. A trap on ERR,if set,is executed before the shell exits.