Skip to content
Vidar Holen edited this page Jul 30, 2023 · 1 revision

var+=1 will append, not increment. Use (( var += 1 )), declare -i var, or quote number to silence.

Problematic code:

var=2 n=3
var+=$n

Correct code:

In bash/ksh, use an (( arithmetic context ))

(( var += n ))

or declare the variable as an integer type:

declare -i var=2
n=4
var+=$n

For POSIX sh, use an $((arithmetic expansion)):

var=$((var+n))

Rationale:

The problematic code attempts to add 2 and 3 to get 5.

Instead, += on a string variable will concatenate, so the result is 23.

Exceptions:

If you do want to concatenate a number, for example to append trailing zeroes, you can silence the warning by quoting the number:

var+="000"

Related resources:

  • Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature guerraart8 to find a specific , or see Checks.

Clone this wiki locally