Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Post Increment

Just a little question about the right way of doing Post-increment in bash.

while true; do
  VAR=$((CONT++))
  echo "CONT: $CONT"
  sleep 1
done

VAR starts at 1 in this case.

CONT: 1
CONT: 2
CONT: 3

But if I do this:

while true; do
  echo "CONT: $((CONT++))"
  sleep 1
done

It starts at 0.

CONT: 0
CONT: 1
CONT: 2

Seems that the the first case is behaving ok, because ((CONT++)) would evaluate CONT (undefined,¿0?) and add +1.

How can I get a behaviour like in echo statement to assign to a variable?

EDIT: In my first example, instead of echoing CONT, I should have echoed VAR, that way it works OK, so it was my error from the beginning.

like image 523
JorgeeFG Avatar asked Aug 24 '26 13:08

JorgeeFG


2 Answers

both cases are OK and reasonable.

foo++ will first return current value (before auto-incrementing) of foo, then auto-increment.

in your 1st case, if you change into echo "CONT: $VAR", it will give same result as case 2.

If you want to have 1,2,3..., with auto-increment, you could try:

echo "CONT: $((++CONT))"
like image 162
Kent Avatar answered Aug 27 '26 00:08

Kent


Let's simplify your code to make it easier to understand.

The following:

  VAR=$((CONT++))
  echo "CONT: $CONT"

can be broken down into the following steps:

  VAR=$CONT            # assign CONT to VAR
  CONT=$((CONT+1))     # increment CONT
  echo "CONT: $CONT"   # print CONT

Similary, the following the statement:

echo "CONT: $((CONT++))"

is equivalent to:

echo "CONT: $CONT"    # print CONT
CONT=$((CONT+1))      # then increment CONT

Hope this helps explain why you see that behaviour.

like image 32
dogbane Avatar answered Aug 26 '26 23:08

dogbane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!