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
I just tested two different ways and both worked for me:
x=$((x+1))
...or...
x=$((++x))
this should do the work
let x=$x+1
-
-
let x=x+1
should belet x=$x+1
. That is likely the reason it is returning one.– BanditMay 22, 2011 at 3:54 -
This might work:
x = `expr $x + 1`
-
-
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 withShift
to enter a tilde (~
).– PatchesMay 22, 2011 at 4:30 -
1
-
-
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 ))