我通常在我的 Bash 脚本中设置 -e
,但偶尔我想运行命令并获取返回值。
不执行 set +e;一些命令;资源=$?; set -e
跳舞,我该怎么做?
最佳答案
来自 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 获取命令的退出状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18621990/