I realise that this question may be down to personal preference but I’m pretty new to Bash / shell scripting so thought it’d be worth some research to see if there’s some sort of standard/best practise or agreeable consensus.
I’m working on a few scripts that I’d eventually like to release open source (probably MIT license) so I’d like the scripts to be “done right”, if there is such a thing.
The script in question has to produce an output text file from a template using variable substitution/expansion to ‘fill in the blanks’ as it were. At present I am using the heredoc
method but I’d like to preserve TAB indents, both in my script and in the output (for readability).
Whilst I have achieved this to a certain extent using cat <<-EOF
to strip the leading tabs (from my script) and by using a variable to store the TAB space (e.g. T="$(printf 't')"
) which I then reference with $T
which is then interpreted correctly within the heredoc back in to a TAB character, I can’t help but think if an external file would just be simpler?
What do any of you more experienced bash scripters can say about it? Which of those practices is better when it comes to the code readibility/maintanance?
Here’s a quick example of what I mean…
my_function() {
T="$(printf 't')"
cat <<- EOF
This is my template for $something
$T I'm indented with the TAB space variable...
$T ...but actually I'm indented twice because the "<<-" only strips the 'leading' tabs
There's something else that I need, but it might be ${printed_literally}/$or_expanded which is cool!
EOF
}
It’s nothing special really, I’m not looking for a ‘solution’ as such, more just some guidance on which solution to use — i.e. heredoc in the script or an external template file?
3
It seems simpler to include all the text relevant to the script inside the script itself,
inside the heredoc, as you did.
Bash scripts are meant to be glue code, nothing too serious and complicated.
If your script is getting serious or complicated,
that’s a sign to consider using a more advanced scripting or programming language.