How-to: Here Documents

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

#!/bin/bash
Command <<MyUniqueLimitString
some text
some more text
MyUniqueLimitString

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.

Examples

Pass multiple lines of text to cat

#!/bin/bash
cat <<End-of-message
--------------------------
The quick brown fox
jumped over the lazy dog
--------------------------
End-of-message

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:

#!/bin/bash
ACTION="Quickly"
cat <<End-of-msg
--------------------------
The quick brown fox $ACTION
jumped over the lazy dog
--------------------------
End-of-msg

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 SS64.com
Some rights reserved