如何在单引号字符串中使用变量?

Pec*_*tum 25 string bash shell echo

我只是想知道如何在单引号内回显变量(我使用单引号,因为字符串中有引号).

     echo 'test text "here_is_some_test_text_$counter" "output"' >> ${FILE}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激

Ign*_*ams 40

变量以双引号字符串扩展,但不在单引号字符串中扩展:

 $ name=World

 $ echo "Hello $name"
 Hello World

 $ echo 'Hello $name'
 Hello $name
Run Code Online (Sandbox Code Playgroud)

如果您只需切换引号,请执行此操作.

如果您更喜欢使用单引号来避免额外的转义,则可以在同一参数中混合和匹配引号:

 $ 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
Run Code Online (Sandbox Code Playgroud)

适用于您的案例:

 echo 'test text "here_is_some_test_text_'"$counter"'" "output"' >> "$FILE"
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记你必须引用``"$ FILE"``. (5认同)
  • 或者,`echo'测试文本\"here_is_some_test_text_ $ counter \"\"output \""`...转义你不希望shell解释的双引号. (2认同)

gle*_*man 7

使用printf:

printf 'test text "here_is_some_test_text_%s" "output"\n' "$counter" >> ${FILE}
Run Code Online (Sandbox Code Playgroud)

  • 请引用``"$ FILE"``. (7认同)