Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

What is the effect of this statement in a shell script?

set -o errtrace
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the manual:

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.

When errtrace is enabled, the ERR trap is also triggered when the error (a command returning a nonzero code) occurs inside a function or a subshell. Another way to put it is that the context of a function or a subshell does not inherit the ERR trap unless errtrace is enabled.

#!/bin/bash

set -o errtrace

function x {
    echo "X begins."
    false
    echo "X ends."
}

function y {
    echo "Y begins."
    false
    echo "Y ends."
}

trap 'echo "ERR trap called in ${FUNCNAME-main context}."' ERR
x
y
false
true

Output:

X begins.
ERR trap called in x.
X ends.
Y begins.
ERR trap called in y.
Y ends.
ERR trap called in main context.

When errtrace is not enabled:

X begins.
X ends.
Y begins.
Y ends.
ERR trap called in main context.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...