Shell Here Documents: Write Multi-Line Text From a Snippet
Quick answer
A here document passes a block of lines to a command as standard input. Start it with << and a delimiter word, write your lines, then close it with a line holding only that word. Add a redirect to turn the block into a file:
cat <<'EOF' > notes.txt
First line
Second line
EOFThe Bash manual gives the general form as [n]<<[-]word: the shell reads input until it finds a line containing only the delimiter, and those lines become the command's standard input. That is all a snippet needs to create a multi-line file.
Step-by-step
Write a multi-line file with cat
Take the example above. cat copies its standard input to its standard output, and > notes.txt sends that output into a file. Run it and notes.txt holds exactly the two lines between the first line and EOF.
Use >> instead of > to append to an existing file rather than replace it.
Pick any delimiter word
EOF and END are conventions, not keywords. Any word works, as long as the closing line contains only that word. The POSIX definition says the here-document ends at a line containing only the delimiter and a newline, with no blank characters in between. A trailing space on the closing line is enough to break it.
If your text itself might contain a line reading EOF, choose a different word, such as END_OF_SNIPPET.
Use it inside a script
Scripts are where here documents earn their keep. They replace a pile of echo lines. Put the interpreter on the first line, as in the #! shebang line, and the here document sits in the body:
#!/bin/sh
cat <<'EOF' > .editorconfig
root = true
[*]
indent_style = space
indent_size = 2
EOFThe optional n in [n]<<word is a file descriptor number. It defaults to standard input, so you rarely write it.
Stack two on one line
POSIX allows more than one here document on a line. The first one is read first, so cat <<eof1; cat <<eof2 takes the text after the line for eof1, then the text for eof2. You'll rarely need it, but it explains why delimiters are matched in order.
Quoted or unquoted delimiter
Unquoted: the body is expanded
When no part of the delimiter word is quoted, the shell expands the body. POSIX lists parameter expansion, command substitution, and arithmetic expansion. A backslash is special only before $, a backtick, another backslash, or a newline, and double quotes are not special at all.
cat <<EOF
Home is $HOME
Sum is $((2 + 3))
EOFThis prints your real home directory and Sum is 5. Great for a template with variables. A nasty surprise for a snippet that contains a literal $.
Quoted: the body is literal
Quote any part of the delimiter word and expansion stops. POSIX says that if any part of the word is quoted, the delimiter is the word after quote removal and the lines are not expanded. So <<'EOF', <<"EOF", and <<\EOF all write the body untouched.
cat <<'EOF' > greet.sh
echo "Hello, $USER"
EOFgreet.sh now contains the text $USER, to be expanded later when the script runs. For pasted snippets, the quoted form is the safer default. The same literal-versus-expanded question comes up for multiline values in a .env file.
Indent with <<-
Inside a function or an if block, a flush-left body looks wrong. The <<- operator fixes that: it strips all leading tab characters from the body lines and from the closing delimiter line, which the Bash manual says allows here-documents in scripts to be indented naturally.
write_config() {
cat <<-'EOF' > app.conf
name = demo
debug = false
EOF
}Every indent in that example is a real tab. Only tabs are stripped, never spaces.
Common problems and fixes
The closing line is not recognized. The shell keeps reading and your command seems to hang, or it fails at the end of the file. Check for trailing blanks after the delimiter. With plain <<, an indented closing line is also not recognized: Wikipedia's example shows a delimiter line that begins with a tab being ignored, so the here document continues. Use <<- with tabs, or move the delimiter to column one.
Unexpected substitutions. If $USER or a backtick turned into real values in your file, the delimiter was unquoted. Quote it: <<'EOF'.
`<<-` stopped working after an edit. An editor or formatter converted your tabs to spaces. Because <<- strips only tabs, the indentation now stays in the file and the closing line no longer matches. Restore real tabs in the body, or drop <<- and keep everything flush left.
You only need one line. Bash also has a here string, <<<, which supplies a single word plus a trailing newline as standard input and needs no delimiter line. Per the Bash manual, the word gets tilde, parameter, and arithmetic expansion and command substitution:
bc <<< "2^10"Here strings are available in Bash, ksh, and zsh, but they are not part of POSIX sh. If your script starts with #!/bin/sh, stick to here documents.
Here documents are old, too. Wikipedia traces them to the Bourne shell in 1979, so they work in nearly every shell you'll meet.
Doing this with Carets
You probably rewrite a here document from memory every few months, and the delimiter and quoting details are easy to forget. Keep a tested copy as a snippet instead: a Markdown file with a fenced bash block holds it, and your code snippets stay in plain Markdown files you can open anywhere.
Carets is a native notes and code editor for iPhone, iPad, and Mac, built for Markdown, plain text, and code in one place. Three features matter here:
- Syntax highlighting for shell and config files, so the delimiter line, the quotes, and the body are easy to tell apart before you run anything.
- Files, projects, and tags to group your shell recipes in one project and find the heredoc snippet by tag.
- Plain text files that stay portable, so tabs you type into a
<<-example are kept as they are, and the file works on any machine you paste it into.
If you use an editor that inserts placeholders, tabstops and placeholders can stand in for the filename or delimiter you change each time.
Get Carets for iPhone, iPad, and Mac on the App Store.
Frequently Asked Questions
What does EOF mean in a here document?
Nothing special. EOF is a conventional delimiter word, short for end of file. Any word works, as long as the closing line contains only that word.
How do I stop the shell from expanding $variables in a here document?
Quote any part of the delimiter word, for example <<'EOF'. The body is then passed through literally, with no parameter expansion, command substitution, or arithmetic expansion.
Can I indent a here document with spaces?
You can indent the body, but <<- strips only leading tabs, not spaces. A closing delimiter indented with spaces is not recognized, so use tabs with <<- or keep the delimiter at the start of the line.
What is the difference between a here document and a here string?
A here document reads many lines up to a delimiter line. A here string, written <<<, passes one word plus a newline as standard input in Bash, ksh, and zsh, and needs no delimiter.