bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Bash' code to store string of any characters containing pair of "" a


From: Greg Wooledge
Subject: Re: Bash' code to store string of any characters containing pair of "" and '' at once
Date: Sat, 21 Dec 2024 13:49:48 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

On Sun, Dec 22, 2024 at 00:49:07 +0700, Budi wrote:
> How is Bash' code to store string of any characters should be containing
> pair of "" and '' at the same time explicitly, being exact verbatim

I'm interpreting this as:

 * You would like to store some data in a string variable.
 * The data is known at script-writing time (i.e. it's a "constant").
 * The data contains both single and double quotes.  (And let's say
   backslashes too, just to avoid another round of questions.)
 * You would like the least ugly solution possible.

So then, you have some choices to make.

For the purpose of this email, let's assume your data looks like this:

    my "payload" has 'single quotes' \inside\ it


Choice #1: use '...' quoting, and change all internal single quotes.
In this form, every ' character must be replaced by the '\'' characters.

    var='my "payload" has '\''single quotes'\'' \inside\ it'


Choice #2: use $'...' quoting, and change all internal single quotes
and backslashes.  In this form, every ' is replaced by \' and every \
is replaced by \\ .

    var=$'my "payload" has \'single quotes\' \\inside\\ it'


Choice #3: use "..." quoting, and change all internal double quotes,
dollar signs, backticks and backslashes.  I won't bother showing this
one because it's a really poor choice.


Choice #4: use a here document.  In this form, the line does not need
any modifications.  However, there is a restriction: it must actually
be a single line of data, with no newlines inside it.

    IFS= read -r var <<'EOF'
    my "payload" has 'single quotes' \inside\ it
    EOF


Choices 1 and 4 are POSIX sh compatible, in case you care about that.
Choice 2 is a bash extension.  Choice 3 is also POSIX compatible, but
it's just bad.

If your data might have internal newlines, then you can extend choice 4
to read multiple lines:

    var=$(cat <<'EOF'
    my "payload" has 'single quotes' \inside\ it
    and one newline
    EOF
    )


At this point, you're forking an external process to assign a constant
to a string variable, so you're pretty deep into "Why am I doing this,
exactly?" territory.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]