Escape backquote in a double-quoted string in shell

╄→гoц情女王★ 提交于 2019-12-18 13:53:27

问题


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 `

回答1:


You need to escape the backtick, but also escape the backslash:

$ touch 1\`
$ /bin/sh -c "ls 1\\\`"
1`

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`

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 `.

I strongly suggest you avoid such filenames in the first place.




回答2:


Use single quotes instead:

/usr/bin/sh -c 'ls 1\`'



回答3:


 /usr/bin/sh -c "ls '1\`'"


来源:https://stackoverflow.com/questions/1824160/escape-backquote-in-a-double-quoted-string-in-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!