Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a script which goes as below...

some function definitions on top and one of them is...

function err_out    
{

 trap 'echo "ERROR in $STEP function. EXITING!";exit 1' ERR    
 #some more messages

 exit 1
}

# Main program starts here
trap 'err_out' ERR

#do something
#call some functions
#call cleanup function
#end of script

when ever some error happens in the functions, they are not propagated and err_out function is not called.

I tried #!/bin/bash -E too; that way when there is an error the script exits but what I need is error to be propagated properly to the handler.

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

From the bash info page:

All other 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.

So you need to set -o errtrace at the top of the script for the ERR trap to be propagated into your functions.

Additionally, you need to be careful about that recursive ERR trap in err_out. Did you really want to set a new trap in the error handler, or did you want to display that message? If the latter, just echo it; the trap would only be invoked if an error occurred in your error handler.

share|improve this answer
    
Yes, but the original poster mentioned that he tried #!/bin/bash -E and the bash manpage mentions: -o errtrace: Same as -E.. So the problem seems to be something else. –  bmk Mar 14 '11 at 20:17
    
See the "Additionally". -E/errprint is necessary but not sufficient. –  geekosaur Mar 14 '11 at 20:18
    
OK - I see, you're right. –  bmk Mar 14 '11 at 20:28
    
Excellent. It works as expected. Thanks a lot geekosaur –  Bashuser Mar 14 '11 at 21:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.