当'set -e'处于活动状态时,Bash获取命令的退出状态? [英] Bash get exit status of command when 'set -e' is active?

查看:193
本文介绍了当'set -e'处于活动状态时,Bash获取命令的退出状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常在Bash脚本中设置了-e,但是偶尔我想运行命令并获取返回值.

I generally have -e set in my Bash scripts, but occasionally I would like to run a command and get the return value.

如果不做set +e; some-command; res=$?; set -e舞蹈,我该怎么做?

Without doing the set +e; some-command; res=$?; set -e dance, how can I do that?

推荐答案

摘自bash手册:

如果失败的命令是在&&中执行的任何命令的一部分,则外壳程序不会退出.或||列出[...].

The shell does not exit if the command that fails is [...] part of any command executed in a && or || list [...].

所以,只需:

#!/bin/bash

set -eu

foo() {
  # exit code will be 0, 1, or 2
  return $(( RANDOM % 3 ))
}

ret=0
foo || ret=$?
echo "foo() exited with: $ret"

示例运行:

$ ./foo.sh
foo() exited with: 1
$ ./foo.sh
foo() exited with: 0
$ ./foo.sh
foo() exited with: 2

这是规范的做法.

这篇关于当'set -e'处于活动状态时,Bash获取命令的退出状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆