2

How can I use ++, +=, *=, etc operators in bash script. Examples please.

Example in C++:

int a = 7;
a = ++a + ++a;
printf("%d", a);
1
  • I'm sorry, but your C++ example is flawed, because the + operator is not a sequence point.
    – elmicha
    May 7, 2011 at 18:36

3 Answers 3

4

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
3
  • I really hope for bash that the first result isn't 7. :P
    – htorque
    May 7, 2011 at 21:21
  • @htorque, good point, in bash a=1; ++a + ++a is 5. May 7, 2011 at 21:38
  • Actually, like in C, the result of ++a + ++a is undefined. Also, there's not really any reason to do two increments on the same variable on the same line.
    – geirha
    May 8, 2011 at 23:29
2
a=7; echo $a
#  7
((a+=a)); echo $a
# 14
((a*=-1)); echo $a
# -14
((++a)); echo $a
# -13
1

It is a wide argument, you should definitely go through bash man page, and through some good bash guide, as this BashGuide

In this page you will find some examples.

You must log in to answer this question.

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