问题
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.
回答1:
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))"
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/15025564/bash-post-increment