Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trap on_error in bash globally?

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?

like image 440
Piotr Dobrogost Avatar asked Feb 14 '14 10:02

Piotr Dobrogost


1 Answers

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.

like image 150
devnull Avatar answered Sep 25 '22 19:09

devnull