Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

How to increment a numeric variable in bash? I tried with var=$var+1 and var=($var+1) but it doesn't work. My variable is a number, but bash think that is a string. My bash version is 4.2.45(1)-release (x86_64-pc-linux-gnu) and I use Ubuntu 13.10.

share|improve this question

2 Answers 2

up vote 64 down vote accepted

There are 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))

or only:

((var=var+1))

or:

((var+=1))

or even:

((var++))

Or you can use let:

let "var=var+1"

or only:

let "var+=1"

or even:

let "var++"

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

share|improve this answer
5  
or ((++var)) or ((var=var+1)) or ((var+=1)). –  gniourf_gniourf Dec 3 '13 at 18:30
    
or var=$(expr $var + 1) –  chilicuil Dec 3 '13 at 23:20
    
Curiously, var=0; ((var++)) returns an error code while var=0; ((var++)); ((var++)) does not. Any idea why? –  phunehehe Mar 26 at 9:36
    
@RaduRădeanu I'm sure, the same thing happens in zsh too. Actually maybe I didn't make myself clear. This prints 1 (an error code) instead of 0 (successful): var=0; ((var++)); echo $?. –  phunehehe Mar 27 at 11:08
4  
@phunehehe Look at help '(('. The last line says: Returns 1 if EXPRESSION evaluates to 0; returns 0 otherwise. –  Radu Rădeanu Mar 27 at 11:41
var=$((var + 1))

Arithmetic in bash uses $((...)) syntax.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.