Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. 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

When pre/post incrementing a variable, in POSIX Shell, what is the difference between these two examples. They seem like they would have the same consequences, but would they be used differently? When would you prefer one over the other?


: $((X=X+1))
share|improve this question
up vote 9 down vote accepted

In your first example, $((X+1)) evaluates the expression X + 1 and expands to the result, which is then asigned to the variable.

In the second example, $((X=X+1)) increments X by one ($((X++)) is also valid and shorter, but not necessarily supported by the shell), then expands to the new value of $X, which is the first argument to the null command, :. The null command ignores its arguments, and the result is discarded (with side effects).

I would personally prefer the first form because of three (relatively subjective) reasons:

  • The null command is obscure and misunderstood, as indicated by its often being the subject of confused questions here.
  • The first form seems more natural in terms of overall shell grammar, and even resembles the old evaluation style a little bit.
  • The first form is clearer and more concise and doesn't involve a command.

You'd have to use the first version if you were modifying the environment of just one command like

X=$((X+1)) /usr/local/bin/something

You'd have to use the second form to add evaluation to arguments directly:

ls -la "file-$((X++))"   # or ...
ls -la "file-$((X=X+1))" # for better compatibility

This has the desired side effects, saves one line, and is pretty clear.

share|improve this answer
+1, seconding the preference for the first form, for all the same reasons. It is important that the assignment operator is guaranteed by POSIX whereas the increment and decrement operators are optional. So, $((X=X+1)) will work on a POSIX-compliant shell, whereas $((X++)) may not. – jw013 Jul 3 '12 at 14:55
Good to know — I'll update. – Alexios Jul 3 '12 at 14:55
@Alexios: Thanks for your help, I have a much better understanding about when to use one vs the other. – TechZilla Jul 3 '12 at 17:38

Your Answer


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.