Bash 中的反引号与大括号 [英] Backticks vs braces in Bash

查看:28
本文介绍了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.

然而,当我尝试

joulesFinal=${echo $joules2 * $cpu | bc}

我收到消息

-bash: ${echo $joules * $cpu | bc}: bad substitution

但是

joulesFinal=`echo $joules2 * $cpu | bc`

工作正常.那么我还需要进行哪些其他更改?

works fine. So what other changes do I need to make?

推荐答案

`` 称为 Command Substitution,相当于 $()(括号),而您正在使用 ${}(花括号).

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.

但是请注意,不推荐使用反引号,而 $() 与 POSIX 兼容,因此您应该更喜欢后者.

Note, though, that backticks are deprecated, while $() is POSIX compatible, so you should prefer the latter.

来自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 中的反引号与大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆