On my system (Ubuntu 17.10) your example just works as desired, both when typed from the command line (into sh
) and when executed as a sh
script:
[bash]§ sh
$ STR="Hello\nWorld"
$ echo $STR
Hello
World
$ exit
[bash]§ echo "STR=\"Hello\nWorld\"
> echo \$STR" > test-str.sh
[bash]§ cat test-str.sh
STR="Hello\nWorld"
echo $STR
[bash]§ sh test-str.sh
Hello
World
I guess this answers your question: it just works. (I have not tried to figure out details such as at what moment exactly the substitution of the newline character for \n
happens in sh
).
However, i noticed that this same script would behave differently when executed with bash
and would print out Hello\nWorld
instead:
[bash]§ bash test-str.sh
Hello\nWorld
I've managed to get the desired output with bash
as follows:
[bash]§ STR="Hello
> World"
[bash]§ echo "$STR"
Note the double quotes around $STR
. This behaves identically if saved and run as a bash
script.
The following also gives the desired output:
[bash]§ echo "Hello
> World"