'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



Solution 1:[1]

use printf:

printf 'test text "here_is_some_test_text_%s" "output"\n' "$counter" >> ${FILE}

Solution 2:[2]

Use a heredoc:

cat << EOF >> ${FILE}
test text "here_is_some_test_text_$counter" "output"
EOF

Solution 3:[3]

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

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

Solution 4:[4]

You can do it this way:

$ counter=1 eval echo `echo 'test text \
   "here_is_some_test_text_$counter" "output"' | \
   sed -s 's/\"/\\\\"/g'` > file

cat file
test text "here_is_some_test_text_1" "output"

Explanation: Eval command will process a string as command, so after the correct amount of escaping it will produce the desired result.

It says execute the following string as command:

'echo test text \"here_is_some_test_text_$counter\" \"output\"'

Command again in one line:

counter=1 eval echo `echo 'test text "here_is_some_test_text_$counter" "output"' | sed -s 's/\"/\\\\"/g'` > file

Solution 5:[5]

Output a variable wrapped with single quotes:

printf "'"'Hello %s'"'" world

Solution 6:[6]

with a subshell:

var='hello' echo 'blah_'`echo $var`' blah blah';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 glenn jackman
Solution 2 William Pursell
Solution 3 Paul Back
Solution 4 Kulimak Joco
Solution 5 Elior Malul
Solution 6