Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Variable in single quote

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.

like image 733
DocWiki Avatar asked Nov 10 '11 18:11

DocWiki


People also ask

How do you use variables in single quotes?

Single quotes:When you enclose characters or variable with single quote ( ' ) then it represents the literal value of the characters. So, the value of any variable can't be read by single quote and a single quote can't be used within another single quotes.

Can you use single quotes in bash?

3.1. 2.2 Single QuotesEnclosing characters in single quotes (' ' ') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

Should you quote variables in bash?

When in doubt, quote your assignments and use quotes + braces together when referencing variables. Yes, it's more verbose, but the braces will remove any doubt on what is a variable and what's a string, it's less ambiguous.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


2 Answers

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' ...
like image 153
William Pursell Avatar answered Sep 30 '22 17:09

William Pursell


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."
like image 21
Gordon Davisson Avatar answered Sep 30 '22 19:09

Gordon Davisson