英文:
\ and $ character in bash script
问题
我有一个脚本:
text=test
echo ""\Plugins$text" 正在计算 ""\Plugins$text""
如何编辑这个命令,以便它显示 `"\Plugins\test\`?
英文:
I have a script:
text=test
echo "\Plugins$text" is couting "\Plugins$text"
How to edit this command, so it displays "\Plugins\test\
?
答案1
得分: 1
Because $text
is a parameter expansion, you need to escape the $
to produce a literal $
; that's what you are currently doing. You want a literal backslash instead; you need to escape the \
itself.
你需要转义 $
,因为 $text
是参数展开,这样才能产生字面的 $
;这是你目前正在做的事情。你想要一个字面的反斜杠,所以你需要转义 \
本身。
You don't need to escape the initial backslash, because \P
has no special meaning in a double-quoted string, and so a literal backslash is retained.
你不需要转义初始的反斜杠,因为在双引号字符串中,\P
没有特殊含义,所以会保留一个字面的反斜杠。
$ echo "\Plugins\\$text"
\Plugins\test
因为 `echo` 的行为在各种不同的 shell 中可以大不相同,如何创建结果中的 `\t` 会变化,所以更好的做法是为了一致性使用 `printf`。
$ printf '%s\n' "\Plugins\$text"
\Plugins\test
英文:
Because $text
is a parameter expansion, you need to escape the $
to produce a literal $
; that's what you are currently doing. You want a literal backslash instead; you need to escape the \
itself.
You don't need to escape the initial backslash, because \P
has no special meaning in a double-quoted string, and so a literal backslash is retained.
$ echo "\Plugins\$text"
\Plugins\test
Because the behavior of echo
can vary wildly from shell to shell in how it creates the resulting \t
, it would be better to use printf
for consistency.
$ printf '%s\n' "\Plugins\$text"
\Plugins\test
答案2
得分: 1
当字符串中可能包含 \
时,我建议使用 printf
而不是 echo
:
text=test
printf ''"\\Plugins\\%s\\ is couting \\Plugins\\%s\\"\n' "$text" "$text"
""\Plugins\test\ is couting \Plugins\test\""
英文:
When the string can contain \
, I would recommend printf
over echo
:
text=test
printf '"\\Plugins\\%s\\ is couting \\Plugins\\%s\\"\n' "$text" "$text"
"\Plugins\test\ is couting \Plugins\test\"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论