How to deal with multiline strings and string interpolation

here-documentstring

Say I want to have a template somewhere which is multiline string:

I have some
text with ${placeholders}
in this and some ${different}
ones ${here} and ${there}

What would be my best way of replacing the placeholders with input from a user? Would here-documents be a good use?

Best Answer

Assuming [a] that no \<newline>, nor the characters \, $, or ` are used in the multiline string (or they are properly quoted), a here-document (and variables) is your best option:

#!/bin/sh

placeholders="value one"
different="value two"
here="value three"
there="value four"

cat <<-_EOT_
I have some
text with ${placeholders}
in this and some ${different}
ones ${here} and ${there}.
_EOT_

If executed:

$ sh ./script
I have some
text with value one
in this and some value two
ones value three and value four.

Of course, correctly playing with qouting, even one variable could do:

$ multilinevar='I have some
> text with '"${placeholders}"'
> in this and some '"${different}"'
> ones '"${here}"' and '"${there}"'.'
$ echo "$multilinevar"
I have some
text with value one
in this and some value two
ones value three and value four.

Both solutions could accept multiline variable placeholders.


[a]From the manual:

... the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `. ...

Related Question