24

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

set -o errtrace
Jani Uusitalo
  • 226
  • 1
  • 9
Rose
  • 403
  • 3
  • 8
  • 4
    The intent is clearly to cause the user to turn to [the documentation](http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin) but it seems to be failing. – tripleee Aug 19 '14 at 08:33

1 Answers1

39

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.
konsolebox
  • 72,135
  • 12
  • 99
  • 105