Bash中的反引号vs括号 [英] Backticks vs braces in Bash
问题描述
当我去回答这个问题时,我将使用${}
表示法,因为我已经在这里看到了很多次,所以比起反引号更合适.
但是,当我尝试
joulesFinal=${echo $joules2 \* $cpu | bc}
我收到了消息
-bash: ${echo $joules * $cpu | bc}: bad substitution
但是
joulesFinal=`echo $joules2 \* $cpu | bc`
正常工作.那么,我还需要进行哪些其他更改?
在使用${}
(花括号)时,``
称为命令替换,等效于$()
(括号). >
所以它们是相等的,意思是解释放置在其中的命令":
joulesFinal=`echo $joules2 \* $cpu | bc`
joulesFinal=$(echo $joules2 \* $cpu | bc)
^ ^
( instead of { ) instead of }
${}
表达式用于变量替换.
来自man bash
:
命令替换允许命令的输出替换 命令名称.有两种形式:
$(command) or `command`
此外,``
更难处理,例如,您不能嵌套它们.参见下面的评论,以及为什么$(...)比...
(反引号)更受欢迎?.
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)?.
这篇关于Bash中的反引号vs括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!