Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape backquote in a double-quoted string in shell

People also ask

How do you escape a double quote in shell?

' appearing in double quotes is escaped using a backslash. The backslash preceding the ' ! ' is not removed. The special parameters ' * ' and ' @ ' have special meaning when in double quotes (see Shell Parameter Expansion).

How do you get out of Backtick in shell?

In tcsh shell script, that triple back slashes method to escape backtick in a double-quoted string in an echo -e (without -e as well) statement did NOT work. However, instead of double-quoted string, using a single quoted string in that echo (without -e) statement, without the need to escape the backtick, worked.

How do you echo double quotes in shell script?

' appearing in double quotes is escaped using a backslash. The backslash preceding the '! ' is not removed. The special parameters '*' and '@' have special meaning when in double quotes (see Shell Parameter Expansion).

How do you escape special characters in shell?

Escape characters. Escape characters are used to remove the special meaning from a single character. A non-quoted backslash, \, is used as an escape character in Bash. It preserves the literal value of the next character that follows, with the exception of newline.


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.


Use single quotes instead:

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