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

后端 未结 13 888
北恋
北恋 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:31

    The problem isn't with the shell. The problem is actually with the echo command itself, and the lack of double quotes around the variable interpolation. You can try using echo -e but that isn't supported on all platforms, and one of the reasons printf is now recommended for portability.

    You can also try and insert the newline directly into your shell script (if a script is what you're writing) so it looks like...

    #!/bin/sh
    echo "Hello
    World"
    #EOF
    

    or equivalently

    #!/bin/sh
    string="Hello
    World"
    echo "$string"  # note double quotes!
    

提交回复
热议问题