此语句在shell脚本中的作用是什么?
set -o errtrace
答案 0 :(得分:16)
从手册:
errtrace Same as -E. -E If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a sub‐ shell environment. The ERR trap is normally not inher‐ ited in such cases.
启用errtrace
时,如果在函数或子shell中发生错误(返回非零代码的命令),也会触发ERR陷阱。换句话说,除非errtrace
已启用,否则函数或子shell的上下文不会继承ERR陷阱。
#!/bin/bash
set -o errtrace
function x {
echo x start
false
echo x end
}
function y {
echo y start
false
echo y end
}
trap 'echo "Error occurred on $FUNCNAME."' ERR
x
y
false
true
输出:
x start
Error occurred on x.
x end
y start
Error occurred on y.
y end
Error occurred on .
未启用errtrace
时:
x start
x end
y start
y end
Error occurred on .