如何在单引号内输出变量?
echo 'test text "here_is_some_test_text_$counter" "output"' >> ${FILE}
在双引号字符串中,变量会被展开,但在单引号字符串中不会:
$ 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"
echo "测试文本 \"这里是一些测试文本_$counter\" \"输出\""
... 转义你不想让 shell 解释的双引号。 - twalberg"$FILE"
。 - Aleks-Daniel Jakimenko-A.使用printf函数:
printf 'test text "here_is_some_test_text_%s" "output"\n' "$counter" >> ${FILE}
使用heredoc:
cat << EOF >> ${FILE}
test text "here_is_some_test_text_$counter" "output"
EOF
最易读、最实用的方式是在双引号内使用花括号。
'test text "here_is_some_test_text_'"${counter}"'" "output"' >> "${FILE}"
在变量周围添加另一对单引号解决了我的问题。
对于您的情况:
echo '测试文本 "这里是一些测试文本_'$counter'" "输出"' >> ${FILE}
输出一个被单引号包裹的变量:
printf "'"'Hello %s'"'" world
$ 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
var='hello' echo 'blah_'`echo $var`' blah blah';
blah_`echo $var` blah blah
- Jonas Berlin$var
中的任何空白字符,请参见Ignacio Vazquez-Abrams的答案。 - Jonas Berlin