The relevant section of man bash
:
In the context where an assignment statement is assigning a value to a
shell variable or array index, the += operator can be used to append to
or add to the variable's previous value. This includes arguments to
builtin commands such as declare that accept assignment statements
(declaration commands). When += is applied to a variable for which the
integer attribute has been set, value is evaluated as an arithmetic ex‐
pression and added to the variable's current value, which is also eval‐
uated. When += is applied to an array variable using compound assign‐
ment (see Arrays below), the variable's value is not unset (as it is
when using =), and new values are appended to the array beginning at
one greater than the array's maximum index (for indexed arrays) or
added as additional key-value pairs in an associative array. When ap‐
plied to a string-valued variable, value is expanded and appended to
the variable's value.
Since you haven't set the integer attribute for a
, a+=$b
will perform string concatenation instead of arithmetic addition:
$ a=1; b=2; a+=$b; echo "$a"
12
whereas
$ unset a b
$ declare -i a=1; b=2; a+=$b; echo "$a"
3
Alternatively, you can force arithmetic evaluation using (( ... ))
$ unset a b
$ a=1; b=2; ((a+=$b)); echo "$a"
3
(note that ((a+=b))
also works; the $
isn't necessary to dereference variables in an arithmetic context).