Add (collect) exit codes in bash

mik picture mik · Jun 16, 2009 · Viewed 11.2k times · Source

I need to depend on few separate executions in a script and don't want to bundle them all in an ugly 'if' statement. I would like to take the exit code '$?' of each execution and add it; at the end, if this value is over a threshold - I would like to execute a command.

Pseudo code:

ALLOWEDERROR=5

run_something
RESULT=$?
..other things..

run_something_else
RESULT=$RESULT + $?

if [ $RESULT -gt ALLOWEDERROR ] 
   then echo "Too many errors"
fi

Issue: Even though the Internet claims otherwise, bash refuses to treat the RESULT and $? as integer. What is the correct syntax?

Thanks.

Answer

Alex Brown picture Alex Brown · Jun 16, 2009

A quick experiment and dip into bash info says:

declare -i RESULT=$RESULT + $?

since you are adding to the result several times, you can use declare at the start, like this:

declare -i RESULT=0

true
RESULT+=$?
false
RESULT+=$?
false
RESULT+=$?

echo $RESULT
2

which looks much cleaner.

declare -i says that the variable is integer.

Alternatively you can avoid declare and use arithmetic expression brackets:

RESULT=$(($RESULT+$?))