How do I assign x the value of x + 1? I can do it in other languages but can't figure it out in bash.

link|improve this question

feedback

4 Answers

up vote 7 down vote accepted

I just tested two different ways and both worked for me:

x=$((x+1))

...or...

x=$((++x))
link|improve this answer
Thanks it worked! – JShoe May 22 '11 at 3:41
feedback

this should do the work

let x=$x+1
link|improve this answer
That gets a return of 1. – JShoe May 22 '11 at 3:39
let x=x+1 should be let x=$x+1. That is likely the reason it is returning one. – Bandit May 22 '11 at 3:54
oops, missed the dollar – freethinker May 22 '11 at 4:24
feedback

This might work:

x = `expr $x + 1`
link|improve this answer
Nope. It assigns what's in the quote to x. – JShoe May 22 '11 at 3:36
1  
@JShoe: Those weren't quotes, they were grave accents. On most keyboards, they're located to the left of the 1 key, on the key you press with Shift to enter a tilde (~). – Patches May 22 '11 at 4:30
1  
Also known as backticks in the context of computing. – Ben Alpert May 22 '11 at 5:54
Another reason not to use backticks anymore, but rather $() ;) – slhck May 22 '11 at 8:53
Though a valid answer, expr is old school. It makes you shell out, an unnecessary process. The syntax in @Bandit 's answer is more modern, and is done in-shell. – Rich Homolka May 27 '11 at 21:45
feedback

@Bandit's answer is fine, but I want to highlight the difference that "let" and (( )) make to normal shell syntax:

let x++

causes bash (or ksh, or any POSIX shell) to treat the expression as an "arithmetic evaluation" in which the referenced variables don't need to be preceeded with "$". One advantage of using (( )) is that otherwise-special tokens don't need to be quoted or escaped, e.g. "*" for multiplication as in:

(( x = x * 2 ))

I find this syntax slightly clearer than $(( )) which uses the output of the expression, e.g.

x=$(( x * 2 ))
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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