What kind of strange shell syntax is hidden behind
$((40-35)) and how come it calculates a value?
$> echo $((40-35)) 5
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
bash man page:
((expression)) 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".
Arithmetic Expansion Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is: $((expression))
Anything put into double parens becomes a math expression that
bash will evaluate.
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
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).