Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

bash - 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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...