Bash:单引号中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8084389/
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
Bash: Variable in single quote
提问by DocWiki
First take a look at this question: Bash or GoogleCL: new line in a string parameter
先看看这个问题: Bash or GoogleCL: new line in a string parameter
I want to add a variable ${date} into the "summary" now:
我现在想在“摘要”中添加一个变量 ${date}:
google youtube post ~/videos/cat-falls-down-stairs.avi Comedy \
--tags 'currency of the internet' \
--summary $'Today is ${date}. Poor whiskers takes a tumble.\nShe'\''s fine, though, don'\''t worry.'
but variable wont expand inside single quote in bash.
但变量不会在 bash 中的单引号内扩展。
Is is possible to do that?
有可能这样做吗?
Note: GoogleCLis a command-line program written in python. I am on Ubuntu 10.10 with Python 2.6.
注意:GoogleCL是一个用 python 编写的命令行程序。我在使用 Python 2.6 的 Ubuntu 10.10。
采纳答案by Gordon Davisson
I'll add yet another option to the list: define a variable as newline, then use that inside double-quotes.
我将在列表中添加另一个选项:将变量定义为换行符,然后在双引号内使用它。
nl=$'\n'
...
--summary "Today is ${date}. Poor whiskers takes a tumble.${nl}She's fine, though, don't worry."
回答by William Pursell
Rather than attempting to expand a variable inside a single quoted string, the typical solution is to concatenate single and double quoted strings. In other words:
典型的解决方案不是尝试在单引号字符串中扩展变量,而是连接单引号和双引号字符串。换句话说:
'Today is'"${date}"'. Poor' ...
回答by bos
Variables are not expanded within single quotes. Either you can do like William suggests, or you can rewrite the line into double quotes, which will expand the variable as you want.
变量不在单引号内展开。您可以按照威廉的建议进行操作,也可以将该行重写为双引号,这将根据需要扩展变量。
"Today is ${date}. Poor whiskers takes a tumble.\nShe's fine, though, don't worry."
Bonus: Doing this way you won't have to escape your single quotes.
奖励:这样做你不必逃避你的单引号。
Now I read the link, and you say \n won't expand. A workaround for that would be something like this:
现在我读了链接,你说 \n 不会扩展。一个解决方法是这样的:
--summary $(echo -e "Today is...")
It's a bit crude to use a subshell for this, but it will save you from backslashing your quotes.
为此使用子shell有点粗糙,但它可以避免您对引号进行反斜杠。

