0

Let's say if I have a code like this.

var=0

while [ condition ] 
do
  ((var+=1))
done

echo $var

How can I increment $var inside the loop and display its value outside of it? Thanks

Let's say if the loop runs for 5 times, my $var, the output should be 5. But now I only got 0 even if the loop runs for like 10 times. $var is just not incremented inside the loop.

  • 1
    +-= is not a valid operator; other than that the code looks ok. (Well, you should put double-quotes around most variable references, like echo "$1", but that's not likely to be a problem in this case.) Can you give a complete example that shows the problem you're seeing? Note that you should trim it down to just the section necessary to show the problem. See How to create a Minimal, Complete, and Verifiable example. – Gordon Davisson May 13 at 6:56
  • Check this answer: askubuntu.com/a/385532/680869 – Romeo Ninov May 13 at 7:17
  • I've edited my question. It was a typo. My apologies – Alex May 13 at 7:20
  • 1
    I'm not able to duplicate the problem. I tested with $var -lt 10 as the condition, and the loop ran ten times (as expected) and printed "10" (as expected). As I said before, please provide an MCVE that shows the problem you're seeing. – Gordon Davisson May 13 at 18:29
1

Both...

cnt=0
while [ $cnt -lt 10 ]
do
  ((cnt++))
done
echo $cnt

...and...

cnt=0
while [ $cnt -lt 10 ]
do
  let cnt=cnt+1
done
echo $cnt

...work.

What $SHELL are you using?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.