Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to set a flag in a shell script (bash) so that if anything returns non-zero, a flag is set (i.e. set a variable like errors="True").

So far, I've thought of calling the script with scriptname.sh 2>Error.log and then doing something like:

 if $(wc -l error.log) != 0; then
   errors="True"

There has got to be a much better way. Please enlighten me.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

This is exactly what trap ERR is for. Unfortunately, it has the same limitations and drawbacks as set -e. Like set -e, any command which returns non-zero in a conditional expression will to trigger the trap. Here is some example code:

error=0
set_error() {
    (( error++ )) 
}

trap set_error ERR
ls askdjasdaj 2>/dev/null
false
false || true # false returns non-zero but is not counted due to the conditional
echo "$error" # outputs "2"
share|improve this answer
    
Thanks! Does trap work for any error caught below the line where trap is? trap -l lists standard signals, I don't see ERR but ERR seems to work. What is ERR considered to be? Is it a signal, or is it shorthand for the file descriptor? –  Gregg Leventhal Nov 1 '13 at 14:08
    
@GreggLeventhal - it's neither, it is special to bash. There are more details in the "trap" section of the bash manpage. –  jordanm Nov 1 '13 at 14:11
    
Sorry, I just read it (or have begun to read it). I am a little confused because errtrace is not set in my shell, I thought I saw that it needed to be set for the ERR keyword to work with trap, but I may have misread that. –  Gregg Leventhal Nov 1 '13 at 14:12

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.