To add a number to a variable in bash, there are many approaches. Some of these are:
Declare variable as integer
Once a variable is is declared as integer (declare -i
), the addition treats it as integer instead of string.
v=1 v+=1 echo "$v" declare -i v v=1 v+=1 echo "$v"
11 2
Env: GNU bash, version 4.2.46
Use bash arithmetic expansion
Use $(()) for bash arithmetic expansion.
v=1 #both $v and v are ok in arithmetic expansion a=$(($v+1)) b=$((v+1)) echo "$a" echo "$b"
2 2
Env: GNU bash, version 4.2.46