Assign variable using multiple lines
Why go for complex, hard-to-read constructs? There is a perfectly natural way to present this which doesn't need any intermediate assignments, fancy ways of building an empty string, quoting subtleties or other cognitive burden.
if foo; then
x=$(
a_very_long_command_name --option1='argument 1 is long' \
--option2='argument 2 is long as well'
)
fi
You can store the value in $_
, which is set to the last argument:
if foo; then
: "$(f)"
x=$_
fi
Or can use a subshell to eat the indent:
if foo; then
x=$(
)$(f)
fi
If you are allowed to use here-docs, the following style works good. Quoting the here-doc string with a leading -
allows your code to be intended with tabs only.
Something like
if true; then
read -d '' -r x <<-EOF
$(f)
EOF
fi
But remember copy pasting the code from above doesn't work as Stack Exchange replaces tabs with spaces. You need to carefully type in the Tab character for the lines starting with the here-doc and the lines ending the here-doc. My vim
configuration has mapped the tab character to 8 spaces. If you want to make it even neater, modify the spacing rule in vim
by setting the spacing for tab to 4 spaces as :set tabstop=4
You can see how the Tab is formatted in my script, by looking into it using sed
$ sed -n l script.sh
#!/usr/bin/env bash$
$
$
f(){$
echo 777$
}$
$
if true; then$
\tread -d '' -r x <<-PERSON$
\t$(f)$
\tPERSON$
fi$
$
echo $x$
Notice the \t
characters in the here-doc string above. If your script looks any different than the above, you would see the whining unexpected EOF
errors.