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 Open Group has a definition for the backtick operator, officially referred to as command substitution. This operator is not the single quote character, but another character known as the grave accent ( ` ).
Bash brace expansion is used to generate stings at the command line or in a shell script. The syntax for brace expansion consists of either a sequence specification or a comma separated list of items inside curly braces "{}". A sequence consists of a starting and ending item separated by two periods "..".
A pair of backticks is a way to refer to names or combinations of symbols that are otherwise reserved or illegal. Reserved are words like if are part of the language, while illegal includes non-syntactic combinations like c a t .
${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol. When a parameter is referenced by a number, it is called a positional parameter.
The ``
is called Command Substitution and is equivalent to $()
(parenthesis), while you are using ${}
(curly braces).
So all of these expressions are equal and mean "interpret the command placed inside":
joulesFinal=`echo $joules2 \* $cpu | bc` joulesFinal=$(echo $joules2 \* $cpu | bc) # v v # ( instead of { v # ) instead of }
While ${}
expressions are used for variable substitution.
Note, though, that backticks are deprecated, while $()
is POSIX compatible, so you should prefer the latter.
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 a specific case:
$ echo "`echo \"test\" `" test $ echo "$(echo \"test\" )" "test"
So backticks silently remove the double quotes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With