Bash echo command not making use of escaped charac

2019-02-27 09:20发布

The bash echo command isn't using the escaped characters like "\n" and "\t"

echo "This is test string\nAnd this is next line"

For the above input it displays

This is test string\nAnd this is next line

So how do I print on the next line?

4条回答
唯我独甜
2楼-- · 2019-02-27 09:47
$ 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.

查看更多
我命由我不由天
3楼-- · 2019-02-27 09:52

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...

查看更多
【Aperson】
4楼-- · 2019-02-27 09:54

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"
查看更多
姐就是有狂的资本
5楼-- · 2019-02-27 09:59

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
查看更多
登录 后发表回答