Writing multi-line strings into a text file in bash script

Published by Bill Glover on

Problem: I wanted to use a shell script to write multi-line strings into a text file. I didn’t want parameters or commands to be substituted in the text being written.

Solution: You need to quote the limit string when specifying your here-document.

References

My fist discovery was that the pattern for doing this in a shell script was called a “Here Document”. I don’t think I have ever looked up the bash manual before. But this is where I found the solution.

Here Documents
       This  type of redirection instructs the shell to read input from the current source
       until a line containing only word (with no trailing blanks) is seen.   All  of  the
       lines read up to that point are then used as the standard input for a command.

       The format of here-documents is:

              <<[-]word
                      here-document
              delimiter

       No  parameter  expansion,  command  substitution, arithmetic expansion, or pathname
       expansion is performed on word.  If any characters in word are quoted,  the  delim-
       iter is the result of quote removal on word, and the lines in the here-document are
       not expanded.  If word is unquoted, all lines of the here-document are subjected to
       parameter expansion, command substitution, and arithmetic expansion.

Example

cat <<EOT
Hi there!
The time is $(date)!
EOT

In this first example the limit string (EOT) has not been quoted and so parameter substitution takes place.

Hi there!
The time is Thu 24 Mar 2022 22:28:30 GMT!

In this second example the limit string ("EOT") has been quoted and so parameter substitution does not take place. Note, that the closing delimiter (EOT) should not be quoted.

cat <<"EOT"
Hi there!
The time is $(date)!
EOT
Hi there!
The time is $(date)!

Further Reading