Solution:
I figured it out. Here is an excerpt from the Bash manual page:
Words of the form $'string' are treated specially. The word expands to
string, with backslash-escaped characters replaced as specified by the
ANSI C standard. Backslash escape sequences, if present, are decoded
as follows:
\a alert (bell)
\b backspace
\e
\E an escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\' single quote
\" double quote
\nnn the eight-bit character whose value is the octal value
nnn (one to three digits)
\xHH the eight-bit character whose value is the hexadecimal
value HH (one or two hex digits)
\cx a control-x character
The expanded result is single-quoted, as if the dollar sign had not
been present.
A double-quoted string preceded by a dollar sign ($"string") will cause
the string to be translated according to the current locale. If the
current locale is C or POSIX, the dollar sign is ignored. If the
string is translated and replaced, the replacement is double-quoted.
Therefore:
$ STR=$'Hello\nWorld'
$ echo "$STR"
Hello
World
Old Answer:
I'm not sure what you can do in order to have escape characters actually reside inside of strings as-typed in your scripts, short of:
STR="$(echo -e 'Hello\nWorld')"
What you can try is this:
$ shopt -s xpg_echo
$ echo "Hello\nWorld"
Hello
World
Or
$ echo -e "Hello\nWorld"
Hello
World
The xpg_echo
shell option "If set, the echo builtin expands backslash-escape sequences by default." (GNU Bash man page). Keep in mind that it doesn't actually insert a newline inside the string; it's what echo
does with the \n
that changes.