# Command substitution and spaces

Why does this work as a calculator:

``````[root@qabun02 ~]# echo \$(( 5+2  ))
7
``````

but this doesn't?

``````[root@qabun02 ~]# echo \$( (5+2) )
``````

The only difference I can see is the absence of space between the brackets?

Also:

```[root@qabun02 ~]# echo \$(who) root pts/0 2015-01-28 09:53 (10.40.0.115) [root@qabun02 ~]# echo \$((who)) 0```

How does command substitution respond to `((` and `( (` ?

The problem is that `\$(` starts command substitution whereas `\$((` starts arithmetic expansion.

`\$( (5+2) )` is the command `(5+2)` i.e. the command `5+2` in a subshell. But that isn't a valid command.

`\$((who))` is replaced by the value of the variable `who` which is probably undefined i.e. 0.

In bash:

`\$(...)` means sub-command substitution (similar to `...`);

`\$((...))` means arithmetic evaluation substitution;

`\${...}` means variable/parameter substitution;

The `\$((` should be seen as an atomic sequence of characters (necessarily terminated by a `))`), it is by no mean equivalent to `\$ ((`, `\$( (` or `\$ ( (`.

OBS: without the `\$` immediately preceding it, a `(` is just a `(` and can be used within a `\$((...))` block to determine precedence of arithmetic evaluation (like `\$(( (3+4)*5 ))` differs from `\$(( 3+4*5 ))`.

• `\$((` is not necessarily atomic. Behaviour for `\$((foo)|(bar))` varies with shells. Jan 28, 2015 at 10:44
• I begin the answer with "in bash:"... :) Jan 28, 2015 at 11:06
• Well, in `bash`, `\$((foo)|(bar))` does process substitution. Jan 28, 2015 at 11:53