How to split strings over multiple lines in Bash?

user880248 picture user880248 · Sep 6, 2011 · Viewed 166.6k times · Source

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

I realize that you can do this:

echo "continuation \
lines"
>continuation lines

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

    echo "continuation \
    lines"
>continuation     lines

Answer

Ray Toal picture Ray Toal · Sep 6, 2011

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.