Here documents and here strings
A here document supplies multiline input directly from script text. Use command <<END followed by lines and a line containing only END. END is an arbitrary delimiter, not a command; do not add trailing spaces. With an unquoted delimiter, parameter, arithmetic and command substitutions are performed on the body. Quoting any part of the opening delimiter disables those expansions; the ending line still uses the delimiter without quotes. <<- strips leading literal TAB characters (not spaces), including on the delimiter line. A here string, command <<< "$value", supplies the expanded value plus one final newline; it does not split into words or expand filename patterns. Here strings are Bash extensions relative to traditional POSIX shell syntax. Use quoted delimiters for literal templates. Do not feed untrusted text to an interpreter just because the delimiter is quoted: quoting controls the shell’s expansion, not the receiving program’s behavior. In an unquoted here-document body, a backslash immediately followed by a newline joins the lines; backslashes can also protect dollar signs, backticks and backslashes. A here string supplies an additional newline even when its value already ends in a newline.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Expanded versus literal text
name=Samcat <<ENDHello $nameTotal: $((2+3))ENDcat <<'END'Hello $nameTotal: $((2+3))ENDExpected stdout:
Hello SamTotal: 5Hello $nameTotal: $((2+3))The first body expands; the second is passed literally.
Strip leading tabs
Expected stdout:
first secondThe example contains actual tab characters; two spaces before second remain.
Read a here string
value=' report * 'IFS= read -r line <<< "$value"printf '[%s]\n' "$line"IFS= read -r empty <<< ''printf 'status=%s value=[%s]\n' "$?" "$empty"Expected stdout:
[ report * ]status=0 value=[]The star stays literal; even the empty string supplies a newline.
Common mistakes
Keep the closing delimiter alone; do not indent it with spaces. Do not write quotes around the closing delimiter. Here strings add a newline even when the value is empty.
Practice
Write one here document expanding a name and a second preserving the literal $name. Then read an empty string via <<< and explain why read succeeds. Use cat or read, not an interpreter.
Next: Descriptor lifetime and exec redirection