2

I have a shell script containing trap, but trap doesn't seems to work as expected below is the code and bash version

GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)

set -e
function exit_message(){
  echo -e "\e[31m\nError occurred "
}
function login(){
  false
}
trap exit_message ERR
login

Above trap works if I do

function login(){
  trap exit_message ERR
  false
}
1
  • no discussion about set -e is complete without a link to this table ;-) Commented Jun 1, 2019 at 21:16

1 Answer 1

3

From the bash manual:

All [...] aspects of the shell execution environment are identical between a function and its caller with these exceptions: the DEBUG and RETURN traps are not inherited unless the function has been given the trace attribute using the declare builtin or the -o functrace option has been enabled with the set builtin, (in which case all functions inherit the DEBUG and RETURN traps), and the ERR trap is not inherited unless the -o errtrace shell option has been enabled.

2
  • I am still not clear what is workaround Commented Jun 1, 2019 at 16:33
  • 2
    set -o errtrace, as it says. Commented Jun 1, 2019 at 17:15

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.