来自 bash 手册页
Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.
考虑到这一点,echo -ne "\n"
是如何产生换行符的?在传递给 echo
之前,shell 不会扩展“\n”吗?
我认为它可能会起作用,因为 echo
是一个内置函数,因此 shell 足够聪明,可以做正确的事情。但是,即使调用外部 /usr/bin/echo -ne "\n"
也可以。
更奇怪的是,无论我用双引号还是单引号 \n
,下面的两个命令都显示 bash 正在传递 \\n
作为参数:
$ strace /usr/bin/echo "\n" 2>&1 | head -n1
execve("/usr/bin/echo", ["/usr/bin/echo", "\\n"], [/* 33 vars */]) = 0
$ strace /usr/bin/echo '\n' 2>&1 | head -n1
execve("/usr/bin/echo", ["/usr/bin/echo", "\\n"], [/* 33 vars */]) = 0
这是怎么回事?
最佳答案
继续阅读:
The backslash retains its special meaning only when followed by one of the following characters:
$
,`
,"
,\
, or<newline>
.
因为它后面跟着一个字母,所以不保留它的特殊含义,而是按字面意思传递给程序。
关于bash - 如果 bash 不在双引号中保留反斜杠,那么为什么 echo -e "\n"起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8632961/