What kind of strange shell syntax is hidden behind $((40-35)) and how come it calculates a value?


$> echo $((40-35))
  • 5
    Open bash manual page and search for ^ *Arithmetic Expansion – enzotib Sep 1 '11 at 17:15
  • In tcsh, it just gives "Illegal variable name." – user2267 Sep 1 '11 at 20:57
  • 2
    Why do you think it is "strange"? It's in the man page. 'man sh' – Jonathan Cline IEEE Sep 1 '11 at 23:21

From the bash man page:

          The expression is evaluated according  to  the  rules  described
          below  under ARITHMETIC EVALUATION.  If the value of the expres-
          sion is non-zero, the return status is 0; otherwise  the  return
          status is 1.  This is exactly equivalent to let "expression".

And further:

  Arithmetic Expansion
    Arithmetic expansion allows the evaluation of an arithmetic expression and
    the substitution of the result.  The format for arithmetic expansion is:


Anything put into double parens becomes a math expression that bash will evaluate.

| improve this answer | |

This is arithmetic expansion. It's supported in all POSIX shells (it didn't exist in the original Bourne shell). The syntax of arithmetic expression is mostly the same as in the C language.

You can use variables with or without a $ in an arithmetic expression. Without a $, a variable stands as a variable, and can in particular be assigned to; for example echo $((a=4)) $a prints 4 4. With a $, the shell performs a simple text expansion; for example a=2+2; echo $(($a)) prints 4 whereas a=2+2; echo $((a)) is an error (but prints 4 on some shells anyway).

The exact rules for deciding whether $(( begins a command substitution ($(command) where the command happens to begin with an opening parenthesis) or an airthmetic expression ($((expression))) vary from shell to shell. If you want to perform a command substitution and the command begins with (, put a space to be safe: $( (echo hello)) (such commands are rare, which is why the syntax could be added without any practical danger of confusion).

| improve this answer | |

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.