&& 和 || 之后的 bash 行续行在哪里 记录在案?

Wil*_*ard 34 bash shell-script

我在脚本中经常看到这个结构并自己使用它,但让我烦恼的是我似乎无法在文档中找到它。

例子:

[ -f file1 ] &&
[ -f file2 ] &&
echo "Both files exist." ||
echo "One or the other file doesn't exist."
Run Code Online (Sandbox Code Playgroud)

这也可以在换行符之前使用反斜杠来完成,如中所述man bash

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).
Run Code Online (Sandbox Code Playgroud)

例子:

[ -f file1 ] && \
[ -f file2 ] && \
echo "Both files exist." || \
echo "One or the other file doesn't exist."
Run Code Online (Sandbox Code Playgroud)

……但这似乎没有必要。即使没有反斜杠,上面的第一个版本也能工作。

我在哪里可以找到这个man bash?(此外,这是bash特定的还是符合 POSIX 的?)

Gil*_*il' 43

在一些明显存在未终止命令的上下文中,换行符会被忽略。这些上下文包括在控制运算符之后(&&, ||, |, &, ;, ;;, 但不是!)。

我在 bash 手册中没有看到这一点。

在 POSIX 中,它是通过语法规则指定的。无论规则在哪里linebreak,您都可以有零个或多个换行符。

  • @OlivierDulac 这怎么可能行得通?当它处理当前命令行时,它如何知道您计划在下一行的开头键入“|”?请记住,shell 也是交互式使用的,而不仅仅是在脚本中,并且语法是相同的。 (2认同)
  • @DocSalvager,我实际上不会使用我编写的代码——它只是一个说明。不过,如果没有最后一行(else 子句),我会这样使用它。(对于“if this and this then do that”`this &amp;&amp; this2 &amp;&amp; that`很好,但对于`else`子句,我会使用实际的`if then else fi`。) (2认同)