问题
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?
回答1:
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
回答2:
$ 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:
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...
回答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"
来源:https://stackoverflow.com/questions/8802308/bash-echo-command-not-making-use-of-escaped-character