加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

评估bash“\u0026\u0026”退出代码行为

发布时间:2020-12-15 18:24:15 所属栏目:安全 来源:网络整理
导读:我们最近有一次关于bash的经历,即使我们找到了一个解决方案,它仍然在扭曲我的想法. bash如何评估表达式的返回码? 执行此脚本,因为myrandomcommand不存在而失败: #!/bin/bashset -eecho "foo"myrandomcommandecho "bar" 结果是预期的一个: ~ bash foo.sh f
我们最近有一次关于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的手册页中阅读:
-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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读