1

I saw this Stack Overflow question regarding the use of parentheses in bash.

Great piece of information but I still have a couple of doubts about how to use parentheses. For instance the below code :

#!/bin/bash
a=5
b=6
c=7
$(( d = a * b + c ))
echo "d : "$d

gave me the output :

./parantheses: line 5: 37: command not found
d : 37

and my research about $(( )) lead me to this site which gave me below piece of information.

$(( expression ))

The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, command substitution, and quote removal. Arithmetic substitutions can be nested.

I didn't quite get it :(
But I did understand that we don't have to use $ before every variable and that the variables will automatically be substituted. What more is to it and why my script is throwing an error?

Also what does a=$( expression ) do?

Does this one too work like $(( ))?

Kindly illustrate the answers with examples so that I can understand better.

Note : I ran the above script in cygwin.

Community
  • 1
  • 1
sjsam
  • 21,411
  • 5
  • 55
  • 102

1 Answers1

4
$(( d = a * b + c ))

After the calculations, what's left is a number, and since that's the first word, the shell will try to execute it, as a command. Not surprisingly, there's no commmand named 37.

You can ignore the result:

: $(( d = a * b + c ))

But it's better to simply write what you meant:

d=$(( a * b + c ))
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • how about `$( )`. How is it different from `$(( ))`? – sjsam Nov 29 '15 at 12:38
  • Thanks for the terminology. I was searching for this indeed. I never knew that `$(..)` superceeded `backticks`. In fact I mastered Linux using an old Linux Bible ;) Thankyou pal !! – sjsam Nov 29 '15 at 12:46