[ACCEPTED]-Add (collect) exit codes in bash-exit-code

Accepted answer
Score: 18

You might want to take a look at the trap builtin 10 to see if it would be helpful:

help trap

or

man bash

you can 9 set a trap for errors like this:

#!/bin/bash

AllowedError=5

SomeErrorHandler () {
    (( errcount++ ))       # or (( errcount += $? ))
    if  (( errcount > $AllowedError ))
    then
        echo "Too many errors"
        exit $errcount
    fi
}

trap SomeErrorHandler ERR

for i in {1..6}
do
    false
    echo "Reached $i"     # "Reached 6" is never printed
done

echo "completed"          # this is never printed

If you count 8 the errors (and only when they are errors) like 7 this instead of using "$?", then you don't 6 have to worry about return values that are 5 other than zero or one. A single return 4 value of 127, for example, would throw you 3 over your threshold immediately. You can 2 also register traps for other signals in addition 1 to ERR.

Score: 17

A quick experiment and dip into bash info 6 says:

declare -i RESULT=$RESULT + $?

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

declare -i RESULT=0

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

echo $RESULT
2

which looks much cleaner.

declare -i says 3 that the variable is integer.

Alternatively 2 you can avoid declare and use arithmetic 1 expression brackets:

RESULT=$(($RESULT+$?))
Score: 2

Use the $(( ... )) construct.

$ cat st.sh
RESULT=0
true
RESULT=$(($RESULT + $?))
false
RESULT=$(($RESULT + $?))
false
RESULT=$(($RESULT + $?))
echo $RESULT
$ sh st.sh
2
$

0

Score: 1

For how to add numbers in Bash also see:

help let 

0

Score: 1

If you want to use ALLOWEDERROR in your 1 script, preface it with a $, e.g $ALLOWEDERROR.

Score: 0

Here are some ways to perform an addition 5 in bash or sh:

RESULT=`expr $RESULT + $?`
RESULT=`dc -e "$RESULT $? + pq"`

And some others in bash only:

RESULT=$((RESULT + $?))
RESULT=`bc <<< "$RESULT + $?"` 

Anyway, exit 4 status on error is not always 1 and its 3 value does not depend on error level, so 2 in the general case there is not much sense 1 to check a sum of statuses against a threshold.

Score: 0

As mouviciel mentioned collecting sum of 4 return codes looks rather senseless. Probably, you 3 can use array for accumulating non-zero 2 result codes and check against its length. Example 1 of this approach is below:

#!/bin/sh

declare RESULT
declare index=0
declare ALLOWED_ERROR=1

function write_result {
    if [ $1 -gt 0 ]; then
        RESULT[index++]=$1
    fi
}

true
write_result $?

false
write_result $?

false
write_result $?

echo ${#RESULT[*]}
if [ ${#RESULT[*]} -gt $ALLOWEDERROR ] 
   then echo "Too many errors"
fi

More Related questions