It seems on_error
trap in Bash works only in the scope of function it was defined in. For instance running this script
#!/bin/bash
on_error() {
echo 'on_error'
}
f() {
false
echo 'function f'
}
g() {
trap on_error ERR
echo 'function g'
false
f
}
g
produces:
function g
on_error
function f
Is there a way to trap on_error
globally so that I don't have to trap it in each function separately?
By default, the ERR
trap isn't inherited by shell functions.
Quoting from help set
:
-E If set, the ERR trap is inherited by shell functions.
-o option-name
Set the variable corresponding to option-name:
errtrace same as -E
Saying
set -o errtrace
at the beginning of your script should make it work as you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With