Home > Mobile >  Recursive Quotation
Recursive Quotation

Time:11-02

When writing bash scripts is there a third level of recursion for double quotes? I need to use double quotes since single quotes will read variables literally.

I can do

"first level \"second level\""

But would like to do something like

"first level \"second level \\" third level \\"\""

I see why that does not work but I need help with syntax

CodePudding user response:

You have to escape the backslash as well.

"first level \"second level \\\" third level \\\"\""

The first \\ makes a literal backslash, then \" escapes the double quote.

CodePudding user response:

Use Here-Documents to Reduce Complexity

Please don't do this at all. Instead, if you need an additional level of quoting, consider:

  1. Correctly intermixing single and double quotes in a way that minimizes the amount of escaping you need to do.
  2. Use a here-document and avoid the whole mess.

I'll cover both, but focus more on the second point, since it's simply easier and less error-prone. For example:

cat <<-'EOF'
first level "second level 'third level'"
EOF

The will avoid interpolation altogether, and correctly prints:

first level "second level 'third level'"

If you're doing something more complex than that, you may want to think about refactoring somewhere else in your code to simplify things. Sometimes complexity is unavoidable, but there's almost always a simpler solution if you take a different approach to the problem.

  • Related