本文介绍了当'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
手册:
所以,只需:
#!/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获取命令的退出状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!