如何在Bash中将字符串分割成多行?

205

如何将我的长字符串常量分成多行?

我知道你可以这样做:

echo "continuation \
lines"
>continuation lines

但是,如果你有缩进的代码,它就不太好用了:

    echo "continuation \
    lines"
>continuation     lines

8
Google的Bash Shell风格指南建议在“如果必须编写超过80个字符的字符串”的情况下使用“here”文档。请参见@tripleee的答案。 - Trevor Boyd Smith
1
https://google.github.io/styleguide/shellguide.html#line-length-and-long-strings -- 这是新文档中的直接链接 - jcollum
1
答案清楚地展示了Bash语言是多么有趣 :-) - matanster
12个回答

0

However, if you have indented code, it doesn't work out so well:

    echo "continuation \
    lines"
>continuation     lines

尝试使用单引号并连接字符串:

    echo 'continuation' \
    'lines'
>continuation lines

注意:连接包括一个空格。

2
它可与 echo 和字符串参数一起使用,但不能处理其他内容,例如变量赋值。尽管问题不涉及变量,但使用 echo 只是一个例子。如果你使用的是 x= 而不是 echo,你会得到错误信息:lines: command not found - Mr. Lance E Sloan
1
@Mr.LanceESloan 这是因为空格没有加引号,所以这实际上是一个不同的问题。 如果在反斜杠之前去掉空格,则此方法也适用于赋值。 - tripleee
Bash 肯定是个浪费时间的东西。 - trusktr

-2

这可能并不完全回答了你的问题,但你可能会发现它仍然很有用。

第一个命令创建了由第二个命令显示的脚本。

第三个命令使该脚本可执行。

第四个命令提供了一个使用示例。

john@malkovich:~/tmp/so$ echo $'#!/usr/bin/env python\nimport textwrap, sys\n\ndef bash_dedent(text):\n    """Dedent all but the first line in the passed `text`."""\n    try:\n        first, rest = text.split("\\n", 1)\n        return "\\n".join([first, textwrap.dedent(rest)])\n    except ValueError:\n        return text  # single-line string\n\nprint bash_dedent(sys.argv[1])'  > bash_dedent
john@malkovich:~/tmp/so$ cat bash_dedent 
#!/usr/bin/env python
import textwrap, sys

def bash_dedent(text):
    """Dedent all but the first line in the passed `text`."""
    try:
        first, rest = text.split("\n", 1)
        return "\n".join([first, textwrap.dedent(rest)])
    except ValueError:
        return text  # single-line string

print bash_dedent(sys.argv[1])
john@malkovich:~/tmp/so$ chmod a+x bash_dedent
john@malkovich:~/tmp/so$ echo "$(./bash_dedent "first line
>     second line
>     third line")"
first line
second line
third line

请注意,如果您真的想使用此脚本,最好将可执行脚本移动到~/bin中,这样它就在您的路径中了。
有关textwrap.dedent的详细信息,请参阅Python参考文档。
如果$'...'"$(...)"的用法令您感到困惑,请提出另一个问题(每个结构一个问题),如果还没有问题,请提供一个链接,以便其他人可以进行参考。

6
尽管这可能是出于良好的意图,甚至可能有用,但原帖询问的是关于基本bash语法的建议,而你提供了一个使用OO范例、异常流控和导入的Python函数定义。此外,你在字符串插值中调用了可执行文件-这是一个提问这种问题的人肯定还没有在bash中见过的东西。 - Parthian Shot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接