7

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

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

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

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

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

有没有一种干净的方法可以防止脚本在这里停止而不取消-e设置并在之后重新设置?

4

1 回答 1

6

是的,在 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
于 2010-12-30T02:48:07.710 回答