Backticks vs braces in Bash

拜拜、爱过 提交于 2020-01-08 14:10:21

问题


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?


回答1:


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




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!