0

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
2
  • 1
    Your sample code can't even run. Please provide a minimal reproducible sample code to illustrate your problem. Commented May 7, 2022 at 3:08
  • 1
    You are probably piping input in to this loop (which you haven't shown). Loops don't necessarily run in a subshell, but commands in a pipeline do. You can solve this by feeding your loop input from a redirection. Either a process substitution: while ... done < <(my-cmd), or a file: while ... done < myfile. Commented May 7, 2022 at 3:49

1 Answer 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, will do some further debugging.
@jTruBela One thing I'd recommend is running your script through shellcheck.net and fixing what it points out. It can also be helpful to put set -x before a problem section to turn on execution tracing (and set +x at the end to turn tracing off).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.