0

Why does this work as a calculator:

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

but this doesn't?

[root@qabun02 ~]# echo $( (5+2) )
-bash: 5+2: command not found

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 ( ( ?

3

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.

1

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 )).

  • 1
    $(( is not necessarily atomic. Behaviour for $((foo)|(bar)) varies with shells. – Stéphane Chazelas Jan 28 '15 at 10:44
  • I begin the answer with "in bash:"... :) – Marcelo Jan 28 '15 at 11:06
  • 1
    Well, in bash, $((foo)|(bar)) does process substitution. – Stéphane Chazelas Jan 28 '15 at 11:53

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.