shell - "set -e"在 shell 和命令替换中

标签 shell robustness

在 shell 脚本中 set -e当从脚本执行的某些命令以非零退出代码退出时,通常用于通过停止脚本来使它们更健壮。

通常很容易通过添加 || true 来指定您不关心某些成功的命令。在末尾。

当您真正关心返回值,但不希望脚本在非零返回码处停止时,就会出现问题,例如:

output=$(possibly-failing-command)
if [ 0 == $? -a -n "$output" ]; then
  ...
else
  ...
fi

在这里,我们既要检查退出代码(因此我们不能在命令替换表达式中使用 || true)并获得输出。但是,如果命令替换中的命令失败,则整个脚本会因 set -e 而停止。 .

有没有一种干净的方法可以防止脚本在不取消设置的情况下停止在这里-e然后把它放回去?

最佳答案

是的,在 if 语句中内联进程替换

#!/bin/bash

set -e

if ! output=$(possibly-failing-command); then
  ...
else
  ...
fi

命令失败
$ ( set -e; if ! output=$(ls -l blah); then echo "command failed"; else echo "output is -->$output<--"; fi )
/bin/ls: cannot access blah: No such file or directory
command failed

指挥工程
$ ( set -e; if ! output=$(ls -l core); then echo "command failed"; else echo "output is: $output"; fi )
output is: -rw------- 1 siegex users 139264 2010-12-01 02:02 core

关于shell - "set -e"在 shell 和命令替换中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4559602/

相关文章:

linux - 使用名称中包含空格的隐藏文件和文件\文件夹

linux - 如果行长于 x 个字符,则剪切并添加字符串

c# - 使用 GetInvocationList 取消订阅事件处理程序

c# - Equals(item, null) 或 item == null

algorithm - 分段线拟合

linux - 在 BASH 中构建简单的计算器

python - 连续执行批处理脚本

shell - 检查文件是否是 Linux 上的链接

c - C 中的字符串处理实践

client-side - 使用 Ember.js 开发的大型网站