Skip to main content

Here Document (here-document, here-text, heredoc, hereis, here-string or here-script) usage and examples in Bash.

#!/usr/bin/env bash

##
# Here Document
#
# A Here Document is used to redirect input into an interactive shell script or
# program.
#
# Here the shell interprets the << operator as an instruction to read input
# until it finds a line containing the specified delimiter. All the input lines
# up to the line containing the delimiter are then fed into the standard input
# of the command.
#
# The delimiter tells the shell that the here document has completed. Without
# it, the shell continues to read the input forever. The delimiter must be a
# single word that does not contain spaces or tabs.
#
# References
#
# - [Shell Input/Output Redirections: Here Document](https://www.tutorialspoint.com/unix/unix-io-redirections.htm)
# - [Advanced Bash-Scripting Guide: Chapter 19. Here Documents](https://tldp.org/LDP/abs/html/here-docs.html)
# - [What does <<EOF do?](https://superuser.com/a/1003761)
##

#########
# Usage #
#########

command <<DELIMITER
...
document
...
DELIMITER

############
# Examples #
############

### Multi-line message, with tabs suppressed

# The `-` option to a here document `<<-` suppresses leading tabs in the body of
# the document, but *not* spaces.

cat <<-EOF
	This is line 1 of the message.
	This is line 2 of the message.
	This is line 3 of the message.
	This is line 4 of the message.
	This is the last line of the message.
EOF

# Above 5 lines of "message" prefaced by a tab, not spaces.
# Spaces not affected by `<<-`.

### Here document with replaceable parameters

NAME="John Doe"
RESPONDENT="the author of this fine script"

cat <<EOF

Hello, there, $NAME.
Greetings to you, $NAME, from $RESPONDENT.

# This comment shows up in the output.

EOF

### Parameter substitution turned off

# Quoting the "limit string" at the head of a here document disables parameter
# substitution within its body. Here's an example.

NAME="John Doe"
RESPONDENT="the author of this fine script"

cat <<'EOF'

Hello, there, $NAME.
Greetings to you, $NAME, from $RESPONDENT.

EOF

### Write a Bash script from a Terminal session and save it to a file

tee script.sh <<EOF
#!/usr/bin/env bash

echo "Hello world!"
exit 0
EOF

# To run the script:
bash script.sh