Here-Documents
A here-document feeds several lines of text to a command's standard input, written directly in the script. It's the cleanest way to create config files, print long messages, or pass SQL, JSON or a script to another program.
Syntax
cat <<EOF
Dear customer,
your order has shipped.
EOFDear customer,
your order has shipped.
<<WORD starts the document; everything up to a line containing only WORD is sent to the command. EOF is the traditional marker, but any word works (END, SQL, CONFIG…).
Expansion: quoted vs unquoted marker
With an unquoted marker, variables, $(...) and $((...)) are expanded inside the text. Quote the marker (<<'EOF') to keep everything literal:
name="Ada"
items=3
cat <<EOF
Hello $name, you have $items items worth \$(( items * 15 )).
EOF
cat <<'EOF'
Literal: $name $(date) stay as written.
EOFHello Ada, you have 3 items worth $45.
Literal: $name $(date) stay as written.
In the unquoted form, \$ produces a literal dollar sign. Use the quoted form whenever the text contains $ signs that belong to something else, for example a shell script you are writing out.
Writing files
Redirect the output of cat to create a file:
app="shop"
port=8080
cat > "$app.service" <<EOF
[Unit]
Description=$app web application
[Service]
ExecStart=/opt/$app/bin/server --port $port
Restart=on-failure
EOF
cat "$app.service"[Unit]
Description=shop web application
[Service]
ExecStart=/opt/shop/bin/server --port 8080
Restart=on-failure
Use >> to append. This pattern is everywhere in provisioning scripts, Dockerfiles (RUN cat > ... <<EOF) and CI pipelines.
Indented here-documents: <<-
Inside functions and if blocks you'd like to indent the text. <<- strips leading tab characters (not spaces) from each line and from the closing marker:
printf 'show_help() {\n\tcat <<-END\n\t\tUsage: tool [options]\n\t\t -h help\n\tEND\n}\nshow_help\n' > help.sh
cat -A help.sh | head -n 3
echo "---"
bash help.shshow_help() {$
^Icat <<-END$
^I^IUsage: tool [options]$
---
Usage: tool [options]
-h help
The example writes the script with printf so the tabs (^I in cat -A) are visible. Many editors convert tabs to spaces, which breaks <<-; if it doesn't work, check for that first.
Here-strings: <<<
For a single line, <<< is shorter:
tr 'a-z' 'A-Z' <<< "quiet please"
read -r user domain <<< "ada example.com"
echo "user=$user domain=$domain"
bc <<< "2^10"QUIET PLEASE
user=ada domain=example.com
1024
Feeding other programs
Any program that reads standard input can take a here-document: bc, awk, sqlite3, python3, psql, ssh host bash…
awk -F, '{ total += $2 } END { print "total:", total }' <<'CSV'
rent,900
food,320
travel,145
CSV
bc <<'CALC'
scale=2
price = 19.99
price * 3
CALC
bash <<'SCRIPT'
for i in 1 2 3; do echo "remote-style step $i"; done
SCRIPTtotal: 1365
59.97
remote-style step 1
remote-style step 2
remote-style step 3
The last example shows the idea behind ssh server bash <<'EOF' ... EOF: a whole script sent to another shell.
Capturing a here-document in a variable
read -r -d '' message <<'EOF' || true
Backup report
=============
All 3 jobs finished.
EOF
echo "$message"
echo "(${#message} characters)"Backup report
=============
All 3 jobs finished.
(48 characters)
read -d '' reads until a null character, which never comes, so it takes the whole document (and returns status 1 at the end, hence || true). An alternative is message=$(cat <<'EOF' ... EOF).
Common mistakes
- Spaces around the closing marker.
EOFmust be alone on its line, with no leading spaces (unless<<-with tabs) and no trailing spaces. - Forgetting to quote the marker when the text contains
$:$1,$PATHor$(...)get expanded when the file is written instead of when it's used.
Test yourself
What is the difference between <<EOF and <<'EOF'?
- None
- With quotes, variables and $(...) are NOT expanded
- With quotes, the text is executed
- Quotes allow indentation
What does <<- do?
- Appends to a file
- Removes leading tab characters from each line
- Removes trailing spaces
- Reads from a file
Which is a here-string?
- cat <<EOF
- wc -w <<< "some words"
- cat < file
- echo > file