Bash:单引号中的变量

5 投票
3 回答
13266 浏览
提问于 2025-04-17 06:03

首先看看这个问题:

Bash或GoogleCL:字符串参数中的换行

我现在想把一个变量 ${date} 加入到“summary”中:

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写的命令行程序。我使用的是Ubuntu 10.10,Python版本是2.6。

3 个回答

1

在单引号里面,变量是不会被展开的。你可以按照William的建议做,或者把这一行改成双引号,这样变量就会像你想的那样被展开。

"Today is ${date}. Poor whiskers takes a tumble.\nShe's fine, though, don't worry."

额外提示:这样做的话,你就不需要对单引号进行转义了。

我看了链接,你提到\n不会被展开。解决这个问题的方法可以是这样的:

--summary $(echo -e "Today is...")

虽然用子shell来处理这个问题有点粗糙,但这样可以让你避免对引号进行反斜杠转义。

15

与其在单引号字符串中尝试扩展一个变量,通常的做法是把单引号和双引号的字符串连接起来。换句话说就是:

'Today is'"${date}"'. Poor' ...
4

我再给这个列表加一个选项:先定义一个变量为换行符,然后在双引号里面使用这个变量。

nl=$'\n'
...
   --summary "Today is ${date}. Poor whiskers takes a tumble.${nl}She's fine, though, don't worry."

撰写回答