So far, I've been using "\""
to print a double quote:
$ x="abc def"
$ echo "x=\"$x\""
x="abc def"
However, it seems like that behavior is undefined?
For echo
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html (ignoring the extra specs for XSI-conformant systems), a backslash leads to outright undefined behavior:
A string to be written to standard output. If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined.
The page for printf
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html refers mostly to the File Format Notation https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap05.html#tag_05 which also doesn't support \"
.
How about the following two methods? Are they explicitly POSIX-compliant?
Concatenating
'
and"
strings$ x="abc def" $ printf x=%s\\n '"'"$x"'"' x="abc def"
Using the octal value for
"
:$ x="abc def" $ printf x=\\42%s\\42\\n "$x" x="abc def"
What are the alternatives?
printf 'x="%s"\n' "$x"
?sh
which I thought defines the "POSIX shell". Is that wrong? (But I think I might understand what you meant about "understanding the shell first". See my comment below.)