When I went to answer this question, I was going to use the ${}
notation, as I've seen so many times on here that it's preferable to backticks.
However, when I tried
joulesFinal=${echo $joules2 \* $cpu | bc}
I got the message
-bash: ${echo $joules * $cpu | bc}: bad substitution
but
joulesFinal=`echo $joules2 \* $cpu | bc`
works fine. So what other changes do I need to make?
The ``
is called Command Substitution and is equivalent to $()
(parenthesis), while you are using ${}
(curly braces).
So these are equal and mean "interpret the command placed inside":
joulesFinal=`echo $joules2 \* $cpu | bc`
joulesFinal=$(echo $joules2 \* $cpu | bc)
^ ^
( instead of { ) instead of }
While ${}
expressions are used for variable substitution.
From man bash
:
Command substitution allows the output of a command to replace the command name. There are two forms:
$(command) or `command`
Also, ``
are more difficult to handle, you cannot nest them for example. See comments below and also Why is $(...) preferred over ...
(backticks)?.
They behave slightly differently in specific case:
$ echo "`echo \"test\" `"
test
$ echo "$(echo \"test\" )"
"test"
so backticks silently remove the double quotes.
来源:https://stackoverflow.com/questions/22709371/backticks-vs-braces-in-bash