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

1 answer

  • answered 2022-05-07 02:40 paxdiablo

    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.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum