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
<<WORDfeeds 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
EOFEverything 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;
EOFis only a habit. - The closing word must sit alone on its line: no spaces before it, nothing after it.
- In an unquoted here document,
$variablesand$( )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$. <<-EOFstrips 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.28The 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.
The goal
The help should say "set
$HOMEto change the target", with the dollar sign visible.
Drills
Answer fast — trust the rule.
With HOME=/home/asha, what does a body line Saved in $HOME print under cat <<'EOF'?
Which closing line correctly ends a here document started with <<EOF?
What does wc -w <<< "one two three" print?
After read -r first rest <<< "alpha beta gamma", what is in rest?
Remember
<<WORDfeeds 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.
