关于linux:`set -o errtrace`在shell脚本中做了什么?

What does `set -o errtrace` do in a shell script?

这个语句在shell脚本中的作用是什么?

1
set -o errtrace


从手册中:

1
2
3
4
5
6
7
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时,当错误(返回非零代码的命令)发生在函数或子外壳内时,也会触发错误陷阱。我们可以说,换句话说,除非启用errtrace,否则函数或子外壳的上下文不会继承错误陷阱。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/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

输出:

1
2
3
4
5
6
7
x start
Error occurred on x.
x end
y start
Error occurred on y.
y end
Error occurred on .

errtrace未启用时:

1
2
3
4
5
x start
x end
y start
y end
Error occurred on .