1
!#/bin/bash
i=1
echo $((i++))

i=1
echo $((++i))

i=1
echo $((i=i+1))

This is the output

bash increment
1
2
2

I thought the expression i=i+1 was identical to i++.

Is there a way to check if two expressions are equal to each other?

2 Answers 2

7

Ok remember that doing a ++i (Pre-Increment) is not the same as i++ (Post-Increment).

Pre-increments will increase the value before output to terminal. Post-Increments will do it after posting it to the terminal. So you will see that the first value is the same as the assign one in the beginning for the first case.

To check this just do this twice:

i=1   
$((i++)) // The output will be 1,2

And then check the rest twice also:

i=1   
$((++i)) // The output will be 2,3

For the echo $((i=i+1)) it will behave the same as a Pre-Increment in the sense that (As shown by the equation) it will assign +1 to the value of 1 and then output the result.

Just to test out the results I made a small script to play with:

x=1
xx=$((x++))

y=1
yy=$((y=y+1))

z=1
zz=$((++z))

echo $xx "Post-Increment"
echo $yy "Y+1 Sum / Same as Pre-Increment"
echo $zz "Pre-Increment"

if [ $xx -eq $yy ]; then
 echo "Post-Increment X equals normal Y+1 method.. yeah right.."
elif [ $xx -eq $zz ]; then
 echo "Post-Increment X equals Pre-Increment Z.. yeah sure..no problem"
elif [ $yy -eq $zz ]; then
 echo "Normal Y+1 method equals Pre-Increment Z.. BINGO! You get a cookie"
fi
1

Traditionally, i++ was a post-increment operator, which meant the new incremented value would not be available until the next reference to it. Whereas the pre-increment operator ++i would make the incremented value available immediately. The use of i=i+1 is not using this logic, because the behavior is specific to the incremental operators.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .