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

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

    Echo is so nineties and so fraught with perils that its use should result in core dumps no less than 4GB. Seriously, echo's problems were the reason why the Unix Standardization process finally invented the printf utility, doing away with all the problems.

    So to get a newline in a string:

    FOO="hello
    world"
    BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
    printf '<%s>\n' "$FOO"
    printf '<%s>\n' "$BAR"
    

    There! No SYSV vs BSD echo madness, everything gets neatly printed and fully portable support for C escape sequences. Everybody please use printf now and never look back.

提交回复
热议问题