shell和命令替换中的“ set -e”

Iva*_*sov 4 shell robustness

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

通常很容易指定您不关心|| true最后添加的某些命令是否成功。

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

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

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

有没有一种干净的方法可以防止脚本在此之前停止而无需取消-e设置然后重新设置呢?

Sie*_*geX 5

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

#!/bin/bash

set -e

if ! output=$(possibly-failing-command); then
  ...
else
  ...
fi
Run Code Online (Sandbox Code Playgroud)

命令失败

$ ( 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
Run Code Online (Sandbox Code Playgroud)

指挥部

$ ( 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
Run Code Online (Sandbox Code Playgroud)