Bash: Variable in single quote

2019-01-19 23:35发布

First take a look at this question: Bash or GoogleCL: new line in a string parameter

I want to add a variable ${date} into the "summary" now:

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.

Is is possible to do that?

Note: GoogleCL is a command-line program written in python. I am on Ubuntu 10.10 with Python 2.6.

3条回答
Deceive 欺骗
2楼-- · 2019-01-19 23:54

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."
查看更多
Animai°情兽
3楼-- · 2019-01-19 23:54

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' ...
查看更多
不美不萌又怎样
4楼-- · 2019-01-19 23:58

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:

--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.

查看更多
登录 后发表回答