Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Here Documents and Here Strings

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

The shortcut

Ask "how much text, and should $ expand?" Several lines: here document. One string: here string. Then choose the end word's quoting: plain EOF expands, 'EOF' keeps it literal.

Printing a literal $HOME in the help textStep 1 of 4
  1. The goal

    The help should say "set $HOME to change the target", with the dollar sign visible.

Drills

Answer fast — trust the rule.

quick drill

With HOME=/home/asha, what does a body line Saved in $HOME print under cat <<'EOF'?

quick drill

Which closing line correctly ends a here document started with <<EOF?

quick drill

What does wc -w <<< "one two three" print?

quick drill

After read -r first rest <<< "alpha beta gamma", what is in rest?

Remember

  • <<WORD feeds lines until WORD; <<< feeds one string.
  • Plain end word expands $; 'EOF' keeps the body literal.
  • Trap: the closing word must be alone on its line, with no spaces around it.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainA help message for backup.sh

Write a here document that prints a three-line usage message for backup.sh, including the real value of $HOME in one line. Explain the rules for the end word, what quoting the end word would change, and give one use of a here string.