如何告诉 bash 该行在下一行继续

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3871332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:43:50  来源:igfitidea点击:

How to tell bash that the line continues on the next line

bash

提问by Open the way

In a bash script I got from another programmer, some lines exceeded 80 columns in length. What is the character or thing to be added to the line in order to indicate that the line continues on the next line?

在我从另一个程序员那里得到的 bash 脚本中,有些行的长度超过了 80 列。要添加到行中以指示该行在下一行继续的字符或事物是什么?

回答by Guillaume

The character is a backslash \

字符是反斜杠 \

From the bash manual:

bash 手册

The backslash character ‘\' may be used to remove any special meaning for the next character read and for line continuation.

反斜杠字符 '\' 可用于删除下一个读取字符和行继续的任何特殊含义。

回答by chepner

In general, you can use a backslash at the end of a line in order for the command to continue on to the next line. However, there are cases where commands are implicitly continued, namely when the line ends with a token than cannot legally terminate a command. In that case, the shell knows that more is coming, and the backslash can be omitted. Some examples:

通常,您可以在行尾使用反斜杠,以便命令继续执行到下一行。但是,在某些情况下命令是隐式继续的,即当行以标记结束时不能合法地终止命令。在这种情况下,shell 知道还有更多内容,并且可以省略反斜杠。一些例子:

# In general
$ echo "foo" \
> "bar"
foo bar

# Pipes
$ echo foo |
> cat
foo

# && and ||
$ echo foo &&
> echo bar
foo
bar
$ false ||
> echo bar
bar

Different, but related, is the implicit continuation inside quotes. In this case, withouta backslash, you are simply adding a newline to the string.

不同但相关的是引号内的隐式延续。在这种情况下,没有反斜杠,您只需在字符串中添加一个换行符。

$ x="foo
> bar"
$ echo "$x"
foo
bar

Witha backslash, you are again splitting the logical line into multiple logical lines.

使用反斜杠,您再次将逻辑行拆分为多个逻辑行。

$ x="foo\
> bar"
$ echo "$x"
foobar

回答by Jingguo Yao

\does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character.Consider this command:

\做这项工作。@Guillaume 的回答和 @George 的评论清楚地回答了这个问题。在这里我解释了为什么The backslash has to be the very last character before the end of line character.考虑这个命令:

   mysql -uroot \
   -hlocalhost      

If there is a space after \, the line continuation will not work. The reason is that \removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \in this example.

如果在 之后有空格\,则续行将不起作用。原因是\删除了下一个字符的特殊含义,该字符是空格而不是不可见的换行符。换行符\在本例中没有的空格之后。