在外壳程序中用双引号引起来的反引号 [英] Escape backquote in a double-quoted string in shell
问题描述
对于命令:/ usr / bin / sh -c ls 1`(1后的反引号)。
For the command: /usr/bin/sh -c "ls 1`" (a backquote after 1).
如何使其成功运行?在`之前添加反斜杠不起作用。
`是我们所知道的特殊字符,我也尝试用单引号将其括起来(/ usr / bin / sh -c ls 1'`'),但这也不起作用。
How to make it run successfully? Adding a backslash before "`" does not work. ` is a special char as we know, and I tried surrounding it with single quote too (/usr/bin/sh -c "ls 1'`'"), but that doesn't work either.
错误始终是:
% /usr/bin/sh -c "ls 1\`"
Unmatched `
推荐答案
您需要避开反引号,但也要避开反斜杠:
You need to escape the backtick, but also escape the backslash:
$ touch 1\`
$ /bin/sh -c "ls 1\\\`"
1`
必须逃跑的原因之所以说两次,是因为您是在一个环境中输入此命令的(例如shell脚本),该环境一次解释了双引号字符串。
The reason you have to escape it "twice" is because you're entering this command in an environment (such as a shell script) that interprets the double-quoted string once. It then gets interpreted again by the subshell.
您也可以避免使用双引号,从而避免第一种解释:
You could also avoid the double-quotes, and thus avoid the first interpretation:
$ /bin/sh -c 'ls 1\`'
1`
另一种方法是将文件名存储在变量中,并使用该值:
Another way is to store the filename in a variable, and use that value:
$ export F='1`'
$ printenv F
1`
$ /bin/sh -c 'ls $F' # note that /bin/sh interprets $F, not my current shell
1`
最后,您尝试的内容将在某些shell上可用(对于上述示例,我使用的是bash),显然不是
And finally, what you tried will work on some shells (I'm using bash, as for the above examples), just apparently not with your shell:
$ /bin/sh -c "ls 1'\`'"
1`
$ csh # enter csh, the next line is executed in that environment
% /bin/sh -c "ls 1'\`'"
Unmatched `.
我强烈建议您在第一名。
这篇关于在外壳程序中用双引号引起来的反引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!