在 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/