Indenting Here-Documents
Problem
The here-document is great, but it’s messing up your shell script’s formatting. You want to be able to indent for readability.
Solution
Use <<- and then you can use tab characters (only!) at the beginning of lines to indent this portion of your shell script.
$ cat myscript.sh ... grep $1 <<-'EOF' lots of data can go here it's indented with tabs to match the script's indenting but the leading tabs are discarded when read EOF ls ... $
Discussion
The hyphen just after the << is enough to tell
bash to ignore the leading tab characters. This is
for tab characters only and not arbitrary white
space. This is especially important with the EOF
or any other marker designation. If you
have spaces there, it will not recognize the EOF
as your ending marker, and the “here” data
will continue through to the end of the file (swallowing the rest of
your script). Therefore, you may want to always left-justify the
EOF
(or other marker) just to be
safe, and let the formatting go on this one line.
Warning
Just as trailing whitespace of any kind on your closing EOF delimiter prevents it from being recognized as the closing delimiter (see the warning in Preventing Weird Behavior in a Here-Document), so too will using a leading character other than just the tab character. If your script indents with spaces or a combination of spaces and tabs, don’t use that technique on here-documents. Either use just tabs, or keep it all flush left. Also, watch out for text editors that automatically ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.