如何在Bash中将字符串拆分成多行? [英] How to split strings over multiple lines in Bash?

查看:611
本文介绍了如何在Bash中将字符串拆分成多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can i split my long string constant over multiple lines?

我知道您可以这样做:

echo "continuation \
lines"
>continuation lines

但是,如果您缩进了代码,那么效果就不太好了:

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

    echo "continuation \
    lines"
>continuation     lines

推荐答案

这可能是您想要的

$       echo "continuation"\
>       "lines"
continuation lines

如果这创建了两个要回显的参数,而您只想要一个,则让我们看一下字符串连接.在bash中,将两个字符串彼此并置:

If this creates two arguments to echo and you only want one, then let's look at string concatenation. In bash, placing two strings next to each other concatenate:

$ echo "continuation""lines"
continuationlines

因此,没有缩进的续行 是拆分字符串的一种方法:

So a continuation line without an indent is one way to break up a string:

$ echo "continuation"\
> "lines"
continuationlines

但是当使用缩进时:

$       echo "continuation"\
>       "lines"
continuation lines

您将获得两个参数,因为这不再是串联.

You get two arguments because this is no longer a concatenation.

如果您想要一个跨行的字符串,同时缩进而不是获得所有这些空格,那么您可以尝试的一种方法是抛弃连续行并使用变量:

If you would like a single string which crosses lines, while indenting but not getting all those spaces, one approach you can try is to ditch the continuation line and use variables:

$ a="continuation"
$ b="lines"
$ echo $a$b
continuationlines

这将使您能够以简洁的方式缩进代码,但会增加其他变量.如果将变量设置为局部变量,应该不会太糟.

This will allow you to have cleanly indented code at the expense of additional variables. If you make the variables local it should not be too bad.

这篇关于如何在Bash中将字符串拆分成多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆