How to escape single quotes in Bash/Grep?

If you do need to look for quotes in quotes in quotes, there are ugly constructs that will do it.

echo 'And I said, "he said WHAT?"'

works as expected, but for another level of nesting, the following doesn’t work as expected:

echo 'She said, "And I said, \'he said WHAT?\'"'

Instead, you need to escape the inner single quotes outside the single-quoted string:

echo 'She said, "And I said, '\''he said WHAT?'\''"'

Or, if you prefer:

echo 'She said, "And I said, '"'"'he said WHAT?'"'"'"'

It ain’t pretty, but it works. 🙂

Of course, all this is moot if you put things in variables.

[ghoti@pc ~]$ i_said="he said WHAT?"
[ghoti@pc ~]$ she_said="And I said, '$i_said'"
[ghoti@pc ~]$ printf 'She said: "%s"\n' "$she_said"
She said: "And I said, 'he said WHAT?'"
[ghoti@pc ~]$ 

🙂

Leave a Comment