How to split strings over multiple lines in Bash?

前端 未结 11 1178
[愿得一人]
[愿得一人] 2020-11-29 16:35

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

I realize that you can do this:

echo "continuation \\
lines"
>continuation li         


        
11条回答
  •  情话喂你
    2020-11-29 17:35

    This is what you may want

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

    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
    

    But when an indent is used:

    $       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.

提交回复
热议问题