Search code examples
bashparentheses

Usage of parentheses in bash


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

Generates the output:

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

My research about $(( )) lead me to this site which has the info below:

$(( 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.

Any other insight? And... why my script is throwing an error?

What does a=$( expression ) do? Does it work like $(( ))?

NOTE: I'm running all the above examples in cygwin.


Solution

  • $(( 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 ))