Increment Variable in Bash – How to Increment a Variable in Bash

bash

I have tried to increment a numeric variable using both var=$var+1 and var=($var+1) without success. The variable is a number, though bash appears to be reading it as a string.

Bash version 4.2.45(1)-release (x86_64-pc-linux-gnu) on Ubuntu 13.10.

Best Answer

There is more than one way to increment a variable in bash, but what you tried is not correct.

You can use for example arithmetic expansion:

var=$((var+1))
((var=var+1))
((var+=1))
((var++))

Or you can use let:

let "var=var+1"
let "var+=1"
let "var++"

See also: http://tldp.org/LDP/abs/html/dblparens.html.