Monday, May 6, 2024
7
rated 0 times [  7] [ 0]  / answers: 1 / hits: 945  / 2 Years ago, thu, december 23, 2021, 6:07:51
!#/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?


More From » command-line

 Answers
2

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

[#41600] Thursday, December 23, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bleger

Total Points: 468
Total Questions: 108
Total Answers: 100

Location: Belarus
Member since Wed, Dec 7, 2022
1 Year ago
;