Skip to the workspace
Pebellslearn by building
Input and Output  ›  Lesson

Here Documents and Here Strings

Here documents 12 minA here document feeds the following lines, up to a chosen end word, to a command's input, and a here string feeds a single string the same way.

shell bash / Here Documents and Here Strings

Explore each scene at your own pace.

01 · The rule

The rule

Here Documents and Here Strings

A here document feeds the following lines, up to a chosen end word, to a command's input, and a here string feeds a single string the same way.

Compare literal and expanded multiline input with a single-string input source.

backup.sh needs a help message that explains how to call it. Five echo lines, each with its own quoting, would be tedious and easy to break. A here document lets you write the text as it should look and feed it straight into a command.

The rule

<<WORD feeds lines until WORD; <<< feeds one string.

cat <<EOF
Usage: backup.sh SOURCE [NAME]
Packs SOURCE into $HOME/backups/NAME-DATE.tar.gz
Example: backup.sh ~/notes notes
EOF

Everything between the first line and the closing EOF becomes the standard input of cat, which prints it. The rules:

  • The end word can be anything; EOF is only a habit.
  • The closing word must sit alone on its line: no spaces before it, nothing after it.
  • In an unquoted here document, $variables and $( ) are expanded, as in double quotes.
  • Quote the end word, <<'EOF', and the body is taken literally, which is useful when the text itself contains $.
  • <<-EOF strips leading tab characters (not spaces), so the body can be indented inside a function.

A here string is the one-line version. It feeds a single string, plus a newline, to a command's input:

line="alpha beta gamma"
read -r first rest <<< "$line"      # first=alpha  rest="beta gamma"
wc -w <<< "$line"                   # 3
bc <<< "scale=2; 30 / 7"            # 4.28
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.