Bash 中的反引号与大括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22709371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backticks vs braces in Bash
提问by rojomoke
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?
工作正常。那么我还需要做哪些其他改变呢?
回答by fedorqui 'SO stop harming'
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.
While${}
表达式用于变量替换。
From man bash
:
来自man bash
:
Command substitutionallows the output of a command to replace the command name. There are two forms:
$(command) or `command`
命令替换允许命令的输出替换命令名称。有两种形式:
$(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)?.
此外,``
更难以处理,例如您不能嵌套它们。请参阅下面的评论以及为什么 $(...) 优于...
(反引号)?.
回答by Gunstick
They behave slightly differently in specific case:
在特定情况下,它们的行为略有不同:
$ echo "`echo \"test\" `"
test
$ echo "$(echo \"test\" )"
"test"
so backticks silently remove the double quotes.
所以反引号默默地删除双引号。