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.

4 Answers 4


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




this should do the work

let x=$x+1
  • That gets a return of 1.
    – JShoe
    May 22, 2011 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, 2011 at 3:54
  • oops, missed the dollar May 22, 2011 at 4:24

This might work:

x = `expr $x + 1`
  • Nope. It assigns what's in the quote to x.
    – JShoe
    May 22, 2011 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, 2011 at 4:30
  • 1
    Also known as backticks in the context of computing. May 22, 2011 at 5:54
  • Another reason not to use backticks anymore, but rather $() ;)
    – slhck
    May 22, 2011 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. May 27, 2011 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 ))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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