在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 - Shell和命令替换中的"set -e",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4559602/

10-12 19:57
查看更多