How can I escape a double quote inside double quotes? How can I escape a double quote inside double quotes? bash bash

How can I escape a double quote inside double quotes?


Use a backslash:

echo "\""     # Prints one " character.


A simple example of escaping quotes in the shell:

$ echo 'abc'\''abc'abc'abc$ echo "abc"\""abc"abc"abc

It's done by finishing an already-opened one ('), placing the escaped one (\'), and then opening another one (').

Alternatively:

$ echo 'abc'"'"'abc'abc'abc$ echo "abc"'"'"abc"abc"abc

It's done by finishing already opened one ('), placing a quote in another quote ("'"), and then opening another one (').

More examples: Escaping single-quotes within single-quoted strings


Keep in mind that you can avoid escaping by using ASCII codes of the characters you need to echo.

Example:

echo -e "This is \x22\x27\x22\x27\x22text\x22\x27\x22\x27\x22"This is "'"'"text"'"'"

\x22 is the ASCII code (in hex) for double quotes and \x27 for single quotes. Similarly you can echo any character.

I suppose if we try to echo the above string with backslashes, we will need a messy two rows backslashed echo... :)

For variable assignment this is the equivalent:

a=$'This is \x22text\x22'echo "$a"# Output:This is "text"

If the variable is already set by another program, you can still apply double/single quotes with sed or similar tools.

Example:

b="Just another text here"echo "$b" Just another text heresed 's/text/"'\0'"/' <<<"$b" #\0 is a special sed operator Just another "0" here #this is not what i wanted to besed 's/text/\x22\x27\0\x27\x22/' <<<"$b" Just another "'text'" here #now we are talking. You would normally need a dozen of backslashes to achieve the same result in the normal way.