来自 bash 联机帮助页
将字符括在双引号中会保留引号内所有字符的字面值,但 $、`、\ 和启用历史扩展时的 ! 除外。
考虑到这一点,echo -ne "\n"
是如何产生换行符的呢? shell 不会在传递给 echo
之前扩展“\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
:这是怎么回事?
From bash manpage
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, !.
With this in mind, how is it that echo -ne "\n"
produces a newline? Wouldn't the shell expand "\n" before it ever gets passed to echo
?
I thought it might work because echo
is a builtin and so the shell is smart enough to do the right thing. However, even calling the external /usr/bin/echo -ne "\n"
works.
What's even more curious is that regardless if I double-quote or single-quote \n
, the following two commands show that bash is passing \\n
as the argument:
$ 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
What's going on here?
发布评论
评论(1)
继续阅读:
因为它后面只是一个字母,所以它不保留其特殊含义,而是按字面意思传递给程序。
Read on:
Since it’s just followed by a letter, it does not retain its special meaning and is passed literally to the program.