为什么 `cat \` return 会提示?

Why does `cat \` return a prompt?

当我 运行 cat \ 在我的终端中时,它 returns 一个换行符和一个提示符 > 我可以在其中输入要打印的文件名。

Echo 也这样做,所以它看起来像是 Unix 的东西。为什么会发生这种情况,这对我一般的 Unix 有什么启示?

我已经阅读了相应的手册页,但没有看到任何内容。谷歌搜索告诉我,由于 shell 解释,尾部的反斜杠必须被转义,而不是那些 shell 解释是什么。

这是 shell 语法。换行符前面的 \(按回车键)转义换行符:

来自man bash

A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows, with the exception of new‐line. If a newline pair appears, and the backslash is not itself quoted, the newline is treated as a line continuation (that is, it is removed from the input stream and effectively ignored).

POSIX:

A backslash that is not quoted shall preserve the literal value of the following character, with the exception of a newline. If a newline follows the backslash, the shell shall interpret this as line continuation. The backslash and newlines shall be removed before splitting the input into tokens. Since the escaped newline is removed entirely from the input and is not replaced by any white space, it cannot serve as a token separator.

这意味着输入命令行还没有完成,shell在下一行继续阅读,显示>提示。

顺便说一下,> 可以通过 PS2 环境变量进行配置。尝试:

$ PS2='(continue cmdline) ... '
$ cat \

PS2 的行为也在 POSIX 中指定:

PS2 Each time the user enters a newline prior to completing a command line in an interactive shell, the value of this variable shall be subjected to parameter expansion and written to standard error. The default value is "> "

反斜杠转义后面的字符,在本例中为换行符(当您按 return 时插入)。它允许您将过长的行换行到多行以提高可读性,例如

echo this is a very long sentence to be\
 printed to your terminal

等同于

echo this is a very long sentence to be printed to your terminal