How-to: Here Documents

A here document is a block of text or code which is redirected to an interactive program or a command.

Command <<MyUniqueLimitString
some text
some more text

The above is equivalent to Command < tempfile.txt where the tempfile contains the text required.

EOF and END are often chosen as the MyUniqueLimitString but any string can be used as long as it does not appear within the here document text.

The - option to mark a here document limit string (<<-LimitString) will suppress leading tabs (but not spaces) in the output. This allows the use of indentation (with tabs) when writing here-documents in shell scripts making them more readable.


Pass multiple lines of text to cat

cat <<End-of-message
The quick brown fox
jumped over the lazy dog

To also write the text to a file, change cat to cat > $filename

Substituting values from a parameter makes it possible to alter the body of the here document:

cat <<End-of-msg
The quick brown fox $ACTION
jumped over the lazy dog

To disable parameter substitution put quotes around the limit string: <<"End-of-message"

Here documents can also be used to supply values to variables or functions.

Related macOS commands

How-to: Here Strings
macOS How To

Copyright © 1999-2024
Some rights reserved