amandawulf
amandawulf

Reputation: 683

Addition Assignment in Bash

In C++, if you have two variables a and b, you can do this to add b to a:

a += b;

How can you do the same thing in bash?

Upvotes: 0

Views: 2231

Answers (4)

Jonathan Callen
Jonathan Callen

Reputation: 11581

If you use the (( ... )) syntax, you don't need to use $ at all before most (simple) variables, so you can do:

a=$((a + b))

or

((a += b))

Upvotes: 1

chrisdotcode
chrisdotcode

Reputation: 1591

Surround the expression in double parenthesis, like so:

a=$(($a + $b))

Alternatively, you could do something like:

(( a+= $b ))

or even:

let a+=$b

Upvotes: 2

ArtemStorozhuk
ArtemStorozhuk

Reputation: 8725

#!/bin/bash
echo "enter two numbers:"
read a b
let a+=$b
echo $a

Upvotes: 1

Ryan
Ryan

Reputation: 1797

Well, a +=b is just a = a + b.

In bash, you can use the following syntax:

a=$(($a+ $b))

Upvotes: 0

Related Questions