Add (collect) exit codes in bash

前端 未结 7 915
执念已碎
执念已碎 2021-02-08 02:28

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 executi

7条回答
  •  再見小時候
    2021-02-08 02:57

    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+$?))
    

提交回复
热议问题