single quote characters in a single-quoted string in shells

A very quick and simple comment on building single-quoted strings in shell scripts which include single quotes.

Note that it’s not possible to include a single quote in a single-quoted string – for example the bash man page:

Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

And dash:

Enclosing characters in single quotes preserves the literal meaning of all the characters (except single quotes, making it impossible to put single-quotes in a single-quoted string).

Which can lead to lots of messy looking strings, especially if changing to using double-quoted strings (which can contain unquoted single quote characters) but then having to carefully (and with some added risk) escape all other special characters:

$ x="all this \$\`\"to include: \"'\" (phew)"
$ echo $x
all this $`"to include: "'" (phew)

The simplest approach I’ve found is to exploit the way that shells auto-concatenate adjacent string-like values which allow single-quotes to be used and just one \ escape per single-quote character needed, simplifying the above example to:

$ x='all this $`"to include: "'\''" (phew)'
$ echo $x
all this $`"to include: "'" (phew)

Which can be done multiple times per string:

$ x='$$$'\''```'\''"""'
$ echo $x
$$$'```'"""

 

Leave a Reply

Your email address will not be published. Required fields are marked *