'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.



Solution 1:[1]

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.

Solution 2:[2]

Post increment means, return the previous value and then increment the value.

In your first example, you use the value after it was incremented. In your second example you use it before you increment it.

If you want the same result as in the first example, you must use prefix increment

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

Solution 3:[3]

((CONT++)) is what increments the variable. Adding the "$" is for other purposes.

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 dogbane
Solution 2 Olaf Dietsche
Solution 3 ychaouche