How can I have a newline in a string in sh?

后端 未结 13 909
北恋
北恋 2020-11-22 17:17

This

STR=\"Hello\\nWorld\"
echo $STR

produces as output

Hello\\nWorld

instead of

Hello
Wo         


        
13条回答
  •  半阙折子戏
    2020-11-22 17:47

    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"
    

提交回复
热议问题