当 'set -e' 处于事件状态时,Bash 获取命令的退出状态?

标签 bash

我通常在我的 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/

相关文章:

bash - 如何在 bash 中撤消 exec 2>/dev/null ?

linux - ps | 和有什么区别? wc 和PS r | Linux 下的 wc ?

bash - 比较两个文件并输出带标记的文件

mysql - 使用 bash 或 awk 从文件读取数据并插入数据库

linux - 使用此处文档为用户提供多种选择

python - 同时运行同一程序的多个版本

java - 如何将显示传递给 qsub 命令?

bash - 在 bash 脚本中使用 `set -e` 命令失败后继续

node.js - 为什么node.js找不到avconv?

bash - 使用 bash 脚本修改配置文件