'Update global variable from while loop

Having trouble updating my global variable in this shell script. I have read that the variables inside the loops run on a sub shell. Can someone clarify how this works and what steps I should take.

USER_NonRecursiveSum=0.0

while [ $lineCount -le $(($USER_Num)) ] 
do
    thisTime="$STimeDuration.$NTimeDuration"
    USER_NonRecursiveSum=`echo "$USER_NonRecursiveSum + $thisTime" | bc`
done


Solution 1:[1]

That particular style of loop does not run in a sub-shell, it will update the variable just fine. You can see that in the following code, equivalent to yours other than adding things that you haven't included in the question:

USER_NonRecursiveSum=0

((USER_Num = 4)) # Add this to set loop limit.
((lineCount = 1)) # Add this to set loop control variable initial value.

while [ $lineCount -le $(($USER_Num)) ]
do
    thisTime="1.2" # Modify this to provide specific thing to add.

    USER_NonRecursiveSum=`echo "$USER_NonRecursiveSum + $thisTime" | bc`

    (( lineCount += 1)) # Add this to limit loop.
done

echo ${USER_NonRecursiveSum} # Add this so we can see the final value.

That loop runs four times and adds 1.2 each time to the value starting at zero, and you can see it ends up as 4.8 after the loop is done.

While the echo command does run in a sub-shell, that's not an issue as the backticks explicitly capture the output from it and "deliver" it to the current shell.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1