bashshellvariablesincrementreturn-code

UNIX shell: increment a variable with value of last returned exit code


Let's say I have a counter initialised by counter=0

Now I want to run a command and increment the value of counter by its returned exit code.

In a natural language I want to do counter = $counter + $?

I am trying stuff like counter=$((counter+$((?)))); but with no success. What is the correct way to do it in a single line?


Solution

  • With bash I suggest:

    counter=$(($counter + $?))
    

    This is also possible:

    counter=$((counter + $?))
    

    Or:

    declare -i counter=0     # set integer attribute
    <your command>
    counter=counter+$?
    

    Or:

    declare -i counter=0
    <your command>
    counter=+$?