Pectus Excavatum
Pectus Excavatum

Reputation: 3785

How do I use variables in single quoted strings?

How do I echo a variable inside single quotes?

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

Upvotes: 52

Views: 89207

Answers (8)

DarkTrick
DarkTrick

Reputation: 3529

Adding another pair of single quotes arround the variable solved my problem.

For your case:

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799390

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"

Upvotes: 86

Elior Malul
Elior Malul

Reputation: 691

Output a variable wrapped with single quotes:

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

Upvotes: 0

Kulimak Joco
Kulimak Joco

Reputation: 9

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

Upvotes: 0

R.Sicart
R.Sicart

Reputation: 681

with a subshell:

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

Upvotes: 0

Paul Back
Paul Back

Reputation: 1319

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

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

Upvotes: 3

William Pursell
William Pursell

Reputation: 212634

Use a heredoc:

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

Upvotes: 4

glenn jackman
glenn jackman

Reputation: 247192

use printf:

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

Upvotes: 7

Related Questions