1

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"""
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user16965639
  • 176
  • 11
  • 1
    There's nothing like triple quotes or raw strings in bash. Why without using backslash? – Barmar Jul 11 '22 at 19:03
  • I may pass huge text which I will copy/paste from somewhere. And adding backslashes to every quote isn't easy. – user16965639 Jul 11 '22 at 19:05
  • 1
    So read the text from stdin rather than making it an argument. – choroba Jul 11 '22 at 19:06
  • you could put it in a file. – Barmar Jul 11 '22 at 19:06
  • The following isn't the most practical solution, so I don't want to submit it as an answer. But you could parse the text and have it add a backslash to escape any quote. – MegaEmailman Jul 11 '22 at 19:06
  • I cannot reproduce `"I can't use "test" text"` is not "terminating double quotes", it is a single argument. Please post how are you checking it? – KamilCuk Jul 11 '22 at 19:08
  • 1
    @KamilCuk If you type `echo "I can't use "test" text"` you won't see the quotes around `test` – Barmar Jul 11 '22 at 19:09
  • Okay, I was hoping there is a way to do it with arguments but I will use alternative methods. Thanks. – user16965639 Jul 11 '22 at 19:11
  • Canonical questions: *[How to escape single quotes within single quoted strings](https://stackoverflow.com/questions/1250079/)* (2009. 26 answers. 1380 votes) and *[How can I escape a double quote inside double quotes?](https://stackoverflow.com/questions/3834839/how-can-i-escape-a-double-quote-inside-double-quotes)* – Peter Mortensen Aug 16 '23 at 19:29
  • Why isn't there *any* attempt to find the duplicate? – Peter Mortensen Aug 16 '23 at 19:31

1 Answers1

1

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

Barmar
  • 741,623
  • 53
  • 500
  • 612