30 shell quotes quoting backticks
对于命令:/ usr/bin/sh -c"ls 1`"(1之后的反引号).
如何让它成功运行?在"`"之前添加反斜杠不起作用.`是我们所知道的一个特殊字符,我也尝试使用单引号将其包围起来(/ usr/bin/sh -c"ls 1'`'"),但这也不起作用.
错误始终是:
% /usr/bin/sh -c "ls 1\`"
Unmatched `
Run Code Online (Sandbox Code Playgroud)
小智 48
你需要逃避反引号,但也逃避反斜杠:
$ touch 1\` $ /bin/sh -c "ls 1\\\`" 1`
您必须"两次"转义它的原因是因为您在一个环境(例如shell脚本)中输入此命令,该环境解释双引号字符串一次.然后由子shell再次解释它.
你也可以避免使用双引号,从而避免第一种解释:
$ /bin/sh -c 'ls 1\`' 1`
另一种方法是将文件名存储在变量中,并使用该值:
$ export F='1`' $ printenv F 1` $ /bin/sh -c 'ls $F' # note that /bin/sh interprets $F, not my current shell 1`
最后,你尝试过的东西会在一些shell上运行(我正在使用bash,就像上面的例子一样),显然不是你的shell:
$ /bin/sh -c "ls 1'\`'" 1` $ csh # enter csh, the next line is executed in that environment % /bin/sh -c "ls 1'\`'" Unmatched `.
我强烈建议你避免这样的文件名首位.