5

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?

Jolta
  • 2,620
  • 1
  • 29
  • 42
Piotr Dobrogost
  • 41,292
  • 40
  • 236
  • 366

1 Answers1

8

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.

devnull
  • 118,548
  • 33
  • 236
  • 227