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

bash – 如果启用了errexit,如何运行可能失败的命令并获取其退出

发布时间:2020-12-15 21:19:59 所属栏目:安全 来源:网络整理
导读:我的所有脚本都打开了errexit;也就是说,我运行set -o errexit.但是,有时我想运行像grep这样的命令,但是即使命令失败也要继续执行我的脚本. 我该怎么做呢?也就是说,如何在不杀死整个脚本的情况下将命令的退出代码转换为变量? 我可以关闭errexit,但我不愿意.
我的所有脚本都打开了errexit;也就是说,我运行set -o errexit.但是,有时我想运行像grep这样的命令,但是即使命令失败也要继续执行我的脚本.

我该怎么做呢?也就是说,如何在不杀死整个脚本的情况下将命令的退出代码转换为变量?

我可以关闭errexit,但我不愿意.

解决方法

如果失败的命令是“未经测试”,则errexit将仅导致脚本终止.每个人都在FreeBSD上:

Exit immediately if any untested command fails in non-interactive
         mode.  The exit status of a command is considered to be explic-
         itly tested if the command is part of the list used to control an
         if,elif,while,or until; if the command is the left hand oper-
         and of an ``&&'' or ``||'' operator; or if the command is a pipe-
         line preceded by the ! keyword.

所以..如果你想使用这样的结构:

grep -q something /path/to/somefile
retval=$?
if [ $retval -eq 0 ]; then
  do_something  # found
else
  do_something_else  # not found
fi

你应该使用这样的结构:

if grep -q something /path/to/somefile; then
  do_something  # found
else
  do_something_else  # not found
fi

if关键字的存在使得grep命令经过测试,因此不受errexit的影响.这种方式需要较少的打字.

当然,如果你真的需要变量中的退出值,那么没有什么能阻止你使用$?:

if grep -q something /path/to/somefile; then
  do_something  # found
else
  unnecessary=$?
  do_something $unnecessary  # not found
fi

(编辑:李大同)

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

    推荐文章
      热点阅读