String 如何在单引号字符串中使用变量?
我只是想知道如何在单引号内回显变量(我使用单引号,因为字符串中有引号)String 如何在单引号字符串中使用变量?,string,bash,shell,echo,String,Bash,Shell,Echo,我只是想知道如何在单引号内回显变量(我使用单引号,因为字符串中有引号) 非常感谢您的帮助变量以双引号字符串展开,但不能以单引号字符串展开: $ name=World $ echo "Hello $name" Hello World $ echo 'Hello $name' Hello $name 如果您可以简单地切换引号,请这样做 如果您喜欢使用单引号来避免额外的转义,则可以在同一个参数中混合并匹配引号: $ echo 'single quoted. '"Double quot
非常感谢您的帮助变量以双引号字符串展开,但不能以单引号字符串展开:
$ name=World
$ echo "Hello $name"
Hello World
$ echo 'Hello $name'
Hello $name
如果您可以简单地切换引号,请这样做
如果您喜欢使用单引号来避免额外的转义,则可以在同一个参数中混合并匹配引号:
$ 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
适用于您的情况:
echo 'test text "here_is_some_test_text_'"$counter"'" "output"' >> "$FILE"
使用printf:
printf 'test text "here_is_some_test_text_%s" "output"\n' "$counter" >> ${FILE}
使用子shell:
var='hello' echo 'blah_'`echo $var`' blah blah';
使用heredoc:
cat << EOF >> ${FILE}
test text "here_is_some_test_text_$counter" "output"
EOF
cat>${FILE}
测试文本“这里是一些测试文本计数器”输出
EOF
最具可读性和功能性的方法是在双引号内使用大括号
'test text "here_is_some_test_text_'"${counter}"'" "output"' >> "${FILE}"
您可以这样做:
$ 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"
说明:
Eval命令将字符串作为命令处理,因此在正确的转义量之后,它将生成所需的结果
它表示将以下字符串作为命令执行:
'echo test text \"here_is_some_test_text_$counter\" \"output\"'
在一行中再次执行命令:
counter=1 eval echo `echo 'test text "here_is_some_test_text_$counter" "output"' | sed -s 's/\"/\\\\"/g'` > file
输出一个用单引号括起来的变量:
printf "'"'Hello %s'"'" world
或者,
echo“test text\”这里\u是一些\u test\u text\uu$counter\“output\”
。。。转义您不希望shell解释的双引号。不要忘记您必须引用“$FILE”
@Aleks-DanielJakimenko-A.@joshdetwiller Long-story short:是的。你链接的答案很好,涉及到所有细节,但引用变量不会有任何伤害,通常情况下,正确的行为确实需要引用引号。请引用“$FILE”
。不起作用,回音blah_`echo$var`blah
你是对的,需要用双引号括起来,而不是简单的引号。我修正了答案。您的新答案将压缩$var
中的所有空格。。请看伊格纳西奥·巴斯克斯·艾布拉姆斯的回答……这是一个错误。你可以用'blah_quez'$var“'blah blah.
但是这已经在伊格纳西奥的答案中了。伊格纳西奥·巴斯克斯·艾布拉姆斯10个月的答案的副本back@JonasBerlin:不完全是重复,但是,鉴于声称的改进是使原始解决方案起作用的偶然结果,这应该是一个评论,不是答案。不幸的是,我没有留下评论的名声。请参阅。如果变量包含文字单引号,则不起作用,因此对于未知值,这是不可靠的。
printf "'"'Hello %s'"'" world