Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backticks vs braces in Bash

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?

like image 603
rojomoke Avatar asked Mar 28 '14 09:03

rojomoke


People also ask

What is backtick in bash?

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

What do braces do in bash?

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

What are Backticks in R?

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 .

What is ${} in bash?

${} 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.


2 Answers

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

like image 171
fedorqui 'SO stop harming' Avatar answered Sep 22 '22 17:09

fedorqui 'SO stop harming'


They behave slightly differently in a specific case:

$ echo "`echo \"test\" `" test  $ echo "$(echo \"test\" )" "test" 

So backticks silently remove the double quotes.

like image 38
Gunstick Avatar answered Sep 22 '22 17:09

Gunstick