bashescapingquotesdouble-quotessingle-quotes

How to escape single and double quotes in Bash


I have a script that takes text as an argument and encodes it. If the text contains only single quotes I surround it with double and vice versa, but it gets tricky if it contains both because it will be closed at first appearance.

script "I can't use "test" text"
// Double quote will be terminated at "I can't use "

So how can I escape both cases without using a backslash, like in Python using triple single, or double quotes.

script '''I can't use "test" text'''
// or
script """I can't use "test" text"""

Solution

  • Use a here-document, and use command subsitution to turn it into an argument.

    script "$(cat <<'EOF'
    I can't use "test" text
    EOF)"
    

    Or