Bash echo命令未使用转义字符

5

bash中的echo命令没有使用转义字符,如"\n"和"\t"

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

对于上述输入,它会显示:
This is test string\nAnd this is next line

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

2
不,这是一个shell编程问题。 - ak2
4个回答

15

如果您想要展开转义字符,那么您需要使用 echo -e

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

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

ANSI-C引用

以$'string'形式的单词会被特殊处理。该单词扩展为字符串,其中的反斜杠转义字符将按照ANSI C标准指定的方式进行替换。


6

echo 命令的具体行为因不同实现而有所区别--一些实现会解释参数中的转义字符,而一些则不会,除非你加上 -e 选项... 如果你试图将其作为选项使用,则某些实现会在输出中打印“-e”。如果要进行任何复杂操作并获得可预测的结果,请改用 printf(请注意,必须显式包含结束换行符):

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

我从一次惨痛的经历中学到了这个教训。当OS X v10.5带来内置 echo 的bash版本时,我的一堆脚本在v10.4下运行良好,但却出现了问题...


0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接