How can I use ++
, +=
, *=
, etc operators in bash script. Examples please.
Example in C++:
int a = 7;
a = ++a + ++a;
printf("%d", a);
In Bash you can do things like:
a=1
echo $((++a + ++a))
# result: 5, but don't write code like that
echo $((a+=4))
echo $((a*=4))
echo $((a/=2))
echo $((a-=1))
a=1; b=1
echo $((++a + ++b)) # Result: 4
echo $((--a + --b)) # Result: 2
a=1; b=1
echo $((a++ + b++)) # Result: 2
echo $((a-- + b--)) # Result: 4
The largest number that bash can handle is
echo $((2**63 - 1))
# Result: 9,223,372,036,854,775,807
++a + ++a
is undefined. Also, there's not really any reason to do two increments on the same variable on the same line.
a=7; echo $a
# 7
((a+=a)); echo $a
# 14
((a*=-1)); echo $a
# -14
((++a)); echo $a
# -13