Frequently Asked Question

What is a heredoc and when should I use one?

A heredoc (here-document) lets you embed a multi-line block of text in a script and feed it to a command's standard input. The syntax is command <<DELIMITER, then the body lines, then a line containing only DELIMITER. The classic use is generating configuration files: cat > /etc/myapp.conf <<EOF followed by the file contents and a closing EOF. Variables and command substitutions inside the body are expanded by default, which is usually what you want.

Two important variants. Writing <<-DELIMITER (with the dash) strips leading tab characters from each body line, so you can indent the heredoc to match surrounding code; only literal tabs are stripped, not spaces, which catches people out. Quoting the delimiter, <<'EOF', disables expansion entirely, treating the body as a literal string; use this when the body contains shell metacharacters you do not want interpreted, such as embedded scripts being passed over SSH or written into another shell's file. Heredocs are far cleaner than long sequences of echo and printf, and should be your default when generating any block of text from a script.

Video

Further reading and video