Bash echo 命令不使用转义字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8802308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:16:13  来源:igfitidea点击:

Bash echo command not making use of escaped character

bashescapingcygwinnewlineecho

提问by Kaymatrix

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

bashecho命令不使用转义字符,如“\n”和“\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?

那么如何在下一行打印呢?

回答by Paul R

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

你需要echo -e,如果你想转义字符进行扩展:

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

回答by kev

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


ANSI-C Quoting

ANSI-C 引用

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.

$'string' 形式的词被特殊处理。单词扩展为字符串,并按照 ANSI C 标准的规定替换反斜杠转义字符。

回答by Gordon Davisson

The echocommand varies quite a bit -- some implementations interpret escape characters in their arguments, some don't unless you add the -eoption... 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 printfinstead (note that you must explicitly include the ending newline):

echo命令改变了不少-一些实现他们的争论中解释转义字符,有的没有,除非你添加-e选项...一些会打印“-e”作为其输出的一部分,如果你尝试使用它作为一个选项. 如果您在做任何重要的事情时想要可预测的结果,请printf改用(请注意,您必须明确包含结尾的换行符):

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 echothat broke a bunch of my scripts that'd worked just fine under v10.4...

我以艰难的方式吸取了这一教训,当 OS X v10.5 附带一个带有内置echo程序的 bash 版本时,它破坏了我在 v10.4 下运行良好的一堆脚本......

回答by JRFerguson

You can use echo -eor you can use the shoptbuilt-in thusly at the beginning of your script:

您可以在脚本的开头使用echo -e或使用shopt内置函数:

shopt -s xpg_echo
...
echo "hello world\n"