在 shell 中转义双引号字符串中的反引号
对于命令: /usr/bin/sh -c "ls 1`" (1 后的反引号)。
怎样才能让它运行成功呢?在“`”之前添加反斜杠不起作用。 正如我们所知, ` 是一个特殊的字符,我也尝试用单引号将它引起来(/usr/bin/sh -c "ls 1'`'"),但这也不起作用。
错误总是:
% /usr/bin/sh -c "ls 1\`"
Unmatched `
For the command: /usr/bin/sh -c "ls 1`" (a backquote after 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.
The error always are:
% /usr/bin/sh -c "ls 1\`"
Unmatched `
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要转义反引号,但也需要转义反斜杠:
您必须“两次”转义它的原因是因为您在解释双引号字符串一次的环境(例如 shell 脚本)中输入此命令。然后它会被子 shell 再次解释。
您还可以避免使用双引号,从而避免第一种解释:
另一种方法是将文件名存储在变量中,并使用该值:
最后,您尝试的内容将在某些 shell 上运行(我正在使用 bash,至于上面的例子),显然不适合你的 shell:
我强烈建议你避免在 第一名。
You need to escape the backtick, but also escape the backslash:
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:
Another way is to store the filename in a variable, and use that value:
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:
I strongly suggest you avoid such filenames in the first place.
使用单引号代替:
Use single quotes instead: