Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 5 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:

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"
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


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.