bash - 如果 bash 不在双引号中保留反斜杠,那么为什么 echo -e "\n"起作用?

标签 bash shell escaping

来自 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/

相关文章:

linux - sudo -H -u git gitosis-init < ~/id_rsa.pub |错误 : no such file or directory

bash - 从 Bash 检查 postgres 查询的结果

linux - Linux中用于获取文件日期的脚本

c# - 防止\r\n 转换为空格

string - 在 Delphi 中的字符串内使用引号

linux - 用另一个文件的内容替换一行

linux - 为什么它总是向我显示存在()的错误?

linux - 通过 Crontab 的 Shell 脚本 - 启动 Jetty,手动工作正常,但不能通过 crontab

javascript - 如何将换行符/回车符插入到 element.textContent 中?

linux - WHO 命令的值在一行中返回(而不是多行)