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
add comment

2 Answers 2

up vote 28 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:

var=$((var+1))

or only:

((var++))

or using let:

let "var=var+1"

or using let and +=:

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

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
3  
@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
show 1 more comment
var=$((var + 1))

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

share|improve this answer
add comment

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.