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
<<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.28