Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Variable Expansion in Single Quote / Double Quote

I want to add a variable ${date} in the following bash script:

ffmpeg -i in.flv -vf drawtext="fontfile=Sans.ttf:text='Today is ${date}':fontsize=6" out.flv

Obviously, ${date} won't expand in single quote, please also note that there is a double quote beyond the single quote, which makes it even more complicated.

Thanks a lot. I am on CentOS 6.

like image 877
Susan Mayer Avatar asked Dec 22 '11 08:12

Susan Mayer


People also ask

How do you pass variables in single quotes in Bash?

If the backslash ( \ ) is used before the single quote then the value of the variable will be printed with single quote.

How do you pass a double quote in Bash?

Single quotes(') and backslash(\) are used to escape double quotes in bash shell script. We all know that inside single quotes, all special characters are ignored by the shell, so you can use double quotes inside it. You can also use a backslash to escape double quotes.

What's the difference between a single quote and a double quote in Bash?

If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.

How do you escape special characters in variable Bash?

Note that the sed pattern I used, 's/[()&]/\\&/g' , only escapes parentheses and ampersands; if your filenames contain any other shell metacharacters, be sure to add them to the character list in [] .


2 Answers

${date} is expanded because it is between double quotes (the single quotes inside the double quotes are just characters)

Test it with:

$ export date=SOMEVALUE
$ echo ffmpeg -i in.flv -vf drawtext="fontfile=/usr/share/fonts/dejavu/DejaVuLGCSans.ttf:text='Today is ${date}':fontsize=6" out.flv
ffmpeg -i in.flv -vf drawtext=fontfile=/usr/share/fonts/dejavu/DejaVuLGCSans.ttf:text='Today is SOMEVALUE':fontsize=6 out.flv
like image 113
Matteo Avatar answered Sep 30 '22 17:09

Matteo


Your ${date} WILL expand correctly. As you said yourself, you surround the whole string with double quotes, and bash will expand variables into double quotes.

The fact that there are inner single quotes does not matter at all:

fg@erwin ~ $ ritchie="Goodbye world"
fg@erwin ~ $ echo "When Dennis passed away, he said '$ritchie'"
When Dennis passed away, he said 'Goodbye world'
like image 22
fge Avatar answered Sep 30 '22 17:09

fge