【问题标题】:Bash: Variable in single quoteBash:单引号中的变量
【发布时间】:2011-12-26 10:19:52
【问题描述】:
首先看一下这个问题:
Bash or GoogleCL: new line in a string parameter
我现在想在“摘要”中添加一个变量 ${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.'
但变量不会在 bash 中的单引号内展开。
有可能吗?
注意:GoogleCL 是一个用 python 编写的命令行程序。我在带有 Python 2.6 的 Ubuntu 10.10 上。
【问题讨论】:
标签:
python
linux
bash
command-line
googlecl
【解决方案1】:
与其尝试在单引号字符串中扩展变量,典型的解决方案是连接单引号和双引号字符串。换句话说:
'今天是'"${date}"'。较差的' ...
【解决方案2】:
我将在列表中添加另一个选项:将变量定义为换行符,然后在双引号内使用它。
nl=$'\n'
...
--summary "Today is ${date}. Poor whiskers takes a tumble.${nl}She's fine, though, don't worry."
【解决方案3】:
变量不在单引号内展开。您可以像 William 建议的那样做,或者您可以将该行重写为双引号,这将根据需要扩展变量。
"Today is ${date}. Poor whiskers takes a tumble.\nShe's fine, though, don't worry."
奖励:这样做您不必转义单引号。
现在我阅读了链接,你说 \n 不会展开。解决方法是这样的:
--summary $(echo -e "Today is...")
为此使用 subshell 有点粗略,但它可以让您免于反斜杠引号。