Bash: split long string argument to multiple lines?

BashMultiline

Bash Problem Overview


Given a command that takes a single long string argument like:

mycommand -arg1 "very long string which does not fit on the screen"

is it possible to somehow split it in a way similar to how separate arguments can be split with \.

I tried:

mycommand -arg1 "very \
long \
string \
which ..."

but this doesn't work.

mycommand is an external command so cannot be modified to take single arguments.

Bash Solutions


Solution 1 - Bash

You can assign your string to a variable like this:

long_arg="my very long string\
 which does not fit\
 on the screen"

Then just use the variable:

mycommand "$long_arg"

Within double quotes, a newline preceded by a backslash is removed. Note that all the other white space in the string is significant, i.e. it will be present in the variable.

Solution 2 - Bash

Have you tried without the quotes?

$ foo() { echo -e "1-$1\n2-$2\n3-$3"; }

$ foo "1 \
2 \
3"

1-1 2 3
2-
3-

$ foo 1 \
2 \ 
3

1-1
2-2
3-3

When you encapsulate it in double-quotes, it's honoring your backslash and ignoring the following character, but since you're wrapping the whole thing in quotes, it's making it think that the entire block of text within the quotes should be treated as a single argument.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionccpizzaView Question on Stackoverflow
Solution 1 - BashTom FenechView Answer on Stackoverflow
Solution 2 - BashEremiteView Answer on Stackoverflow