Bash echo命令不使用转义字符

Kay*_*rix 3 bash cygwin newline escaping echo

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

echo "This is test string\nAnd this is next line"
Run Code Online (Sandbox Code Playgroud)

对于上面的输入,它会显示

This is test string\nAnd this is next line
Run Code Online (Sandbox Code Playgroud)

那么如何在下一行打印?

Pau*_*l R 12

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

$ echo -e "This is test string\nAnd this is next line"
This is test string 
And this is next line
Run Code Online (Sandbox Code Playgroud)


kev*_*kev 6

$ echo $'This is test string\nAnd this is next line'
This is test string
And this is next line
Run Code Online (Sandbox Code Playgroud)

ANSI-C引用

$'string'形式的单词是专门处理的.单词扩展为字符串,替换为ANSI C标准指定的反斜杠转义字符.


Gor*_*son 5

echo命令有很大的不同-有些实现解释其参数中的转义字符,有些除非添加-e选项,否则不解释...如果尝试将其用作选项,某些实现将在输出中显示“ -e” 。如果在进行任何重要操作时都希望得到可预期的结果,请printf改用(请注意,您必须明确地包括结尾的换行符):

printf "This is test string\nAnd this is next line\n"
Run Code Online (Sandbox Code Playgroud)

当OS X v10.5附带一个带有内置功能的bash版本时,我很难学到这一课,这使echo我的一堆脚本无法在v10.4下正常工作。