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

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


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:

set_error() {
    (( error++ )) 

trap set_error ERR
ls askdjasdaj 2>/dev/null
false || true # false returns non-zero but is not counted due to the conditional
echo "$error" # outputs "2"
  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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