Bash - Removing white space from indented multiline strings

Viewed 2900

This may be a more general question so sorry in advance. I am creating a script and thought it would be good to use multi-line strings instead of using multiple printf or echo statements. Say I have the following:

while :
do
 printf "line 1
 line 2
 line 3"
done

The second and third lines would be printed with a space in front because of the indentation in the file.

l1
 line 2
 line 3

Is there a way to prevent that aside from removing the indentation on the code? Also, is it considered a better practice to just multiple printf/echo statements if you need to output information that spans multiple lines?

2 Answers

Indent with tabs (here whitespace) and use a heredoc (with <<-)

cat <<- EOF
  line 1
  line 2
  line 3
EOF

Multi-line strings will always look a bit bad, or have some other downsides, I'm afraid. The most legible way to embed them in bash code is probably the here-doc, which shows the string (almost) exactly like it will look when output. As an extra knack, you can use extra punctuation to make the here-doc delimiter to stand out from the string itself too, like so:

if true
then
    some commands

    cat <<"____EndOfTextBlock____"
This text here
spans multiple        
lines.
____EndOfTextBlock____

    some other commands
    even more commands
fi
Related