Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 7 down vote accepted

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

x=$((x+1))

...or...

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

this should do the work

let x=$x+1
share|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

This might work:

x = `expr $x + 1`
share|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

@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 ))
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .