Bash echo command not making use of escaped character

我是研究僧i 提交于 2019-12-01 07:54:54

You need echo -e if you want escaped characters to be expanded:

$ echo -e "This is test string\nAnd this is next line"
This is test string 
And this is next line
$ echo $'This is test string\nAnd this is next line'
This is test string
And this is next line

ANSI-C Quoting

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.

The echo command varies quite a bit -- some implementations interpret escape characters in their arguments, some don't unless you add the -e option... some will print "-e" as part of their output if you try to use it as an option. If you want predictable results when doing anything nontrivial, use printf instead (note that you must explicitly include the ending newline):

printf "This is test string\nAnd this is next line\n"

I learned this lesson the hard way, when OS X v10.5 came with a version of bash with a builtin echo that broke a bunch of my scripts that'd worked just fine under v10.4...

You can use echo -e or you can use the shopt built-in thusly at the beginning of your script:

shopt -s xpg_echo
...
echo "hello world\n"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!