Bash: split long string argument to multiple lines?

ccpizza picture ccpizza · Oct 18, 2017 · Viewed 32.7k times · Source

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.

Answer

Tom Fenech picture Tom Fenech · Oct 18, 2017

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.