Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use variables in single quoted strings?

I am just wondering how I can echo a variable inside single quotes (I am using single quotes as the string has quotation marks in it).

echo 'test text "here_is_some_test_text_$counter" "output"' >> ${FILE}

any help would be greatly appreciated

like image 614
Pectus Excavatum Avatar asked Jan 17 '14 17:01

Pectus Excavatum


People also ask

How do you use variables in single quotes?

When the variable is quoted by single quote then the variable name will print as output. If the backslash ( \ ) is used before the single quote then the value of the variable will be printed with single quote.

Can you use single quotation marks to declare a string variable?

Quotation marks are used to specify a literal string. You can enclose a string in single quotation marks ( ' ) or double quotation marks ( " ).

How do you handle a single quote in a string?

Use escapeEcmaScript method from Apache Commons Lang package: Escapes any values it finds into their EcmaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.). So a tab becomes the characters '\\' and 't' .


4 Answers

Variables are expanded in double quoted strings, but not in single quoted strings:

 $ name=World   $ echo "Hello $name"  Hello World   $ echo 'Hello $name'  Hello $name 

If you can simply switch quotes, do so.

If you prefer sticking with single quotes to avoid the additional escaping, you can instead mix and match quotes in the same argument:

 $ echo 'single quoted. '"Double quoted. "'Single quoted again.'  single quoted. Double quoted. Single quoted again.   $ echo '"$name" has the value '"$name"  "$name" has the value World 

Applied to your case:

 echo 'test text "here_is_some_test_text_'"$counter"'" "output"' >> "$FILE" 
like image 146
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 07:09

Ignacio Vazquez-Abrams


use printf:

printf 'test text "here_is_some_test_text_%s" "output"\n' "$counter" >> ${FILE}
like image 42
glenn jackman Avatar answered Sep 28 '22 06:09

glenn jackman


Use a heredoc:

cat << EOF >> ${FILE}
test text "here_is_some_test_text_$counter" "output"
EOF
like image 29
William Pursell Avatar answered Sep 28 '22 05:09

William Pursell


The most readable, functional way uses curly braces inside double quotes.

'test text "here_is_some_test_text_'"${counter}"'" "output"' >> "${FILE}"
like image 43
Paul Back Avatar answered Sep 28 '22 06:09

Paul Back