Search code examples
bashescapingquotesdouble-quotes

How to escape double quotes inside escaped doubles quotes inside double quotes?


I try to execute the following command :

su -l user1 -c "hive -e \"ALTER TABLE schema1.table1 DROP IF EXISTS PARTITION (att1=\"$val\");\""

I get the error :

FAILED: ParseException line 1:81 cannot recognize input near 'val1' ')' '<EOF>' in constant

So the problem here is due to the 2nd level nested double quotes, between which there is the variable $val whose value is val1.

Can you help me resolve it? And the best is to give me a rule for nested quotes.


Solution

  • In this particular case, you can use single quotes instead of the internal (currently escaped) double quotes, since single quotes inside double quotes are not special at all.

    su -l user1 -c "hive -e 'ALTER TABLE schema1.table1 DROP IF EXISTS PARTITION (att1=\"$val\");'"
    

    In the general case, you can't always avoid death by backslash escapes. The general quoting rules are very straightforward; text between single quotes is quoted verbatim, whereas double quotes are weaker but allow you to backslash things which should not be touched by the shell.