shBash
AdvancedLesson 12 of 15

Here-Docs, Process Substitution & Debugging – Bash

Embed multi-line text, treat command output like files and debug scripts.

A here-document (<<EOF) passes multi-line text to stdin. If the end word is in single quotes (<<'EOF'), nothing is expanded; without quotes, variables and $(...) are substituted. With <<-, tab indentation may be stripped. A here-string <<< passes exactly one string.

version="1.2"
cat > config.ini <<EOF
[app]
version=$version
erstellt=$(date +%F)
EOF

cat <<'EOF'
Here, $version is NOT replaced.
EOF

grep -c "a" <<< "banana bandana"     # 1   (one line; grep -c counts lines)
read -r vorname nachname <<< "Ada Lovelace"
echo "$nachname, $vorname"           # Lovelace, Ada

Process substitution <(command) provides the output of a command as a temporary "file" – handy for programs that expect file names instead of stdin. >(command) works the other way round. It also protects against the subshell trap with while read:

diff <(sort a.txt) <(sort b.txt)          # compare sorted versions
comm -12 <(sort liste1) <(sort liste2)       # common lines

# Trap: the pipe creates a subshell, the counter is lost
zaehler=0
printf 'a\nb\nc\n' | while read -r x; do zaehler=$((zaehler + 1)); done
echo "$zaehler"                              # 0 !

# Solution: process substitution (or redirect a file)
zaehler=0
while read -r x; do zaehler=$((zaehler + 1)); done < <(printf 'a\nb\nc\n')
echo "$zaehler"                              # 3

Debugging: bash -n script.sh checks only the syntax, bash -x script.sh (or set -x in the script) shows every executed command with expanded variables. PS4 customizes the prefix, set +x switches back. ShellCheck finds most errors before you even run the script.

#!/usr/bin/env bash
set -euo pipefail
PS4='+ $(date +%T) ${BASH_SOURCE[0]##*/}:$LINENO: '   # timestamp, file and line number
set -x
x=$((2 + 3))
echo "x=$x"
set +x
# Output (stderr):  + 12:00:01 test.sh:5: x=5
#                    + 12:00:01 test.sh:6: echo x=5
WarningHere-docs with an indented end word only work with <<- and tabs, not with spaces. The end word must be alone on its line, with no spaces before or after it.
TipIf you need a lot of text in a script, consider printf instead of echo: printf '%s\n' "$var" behaves consistently (with echo -n, -e shells and systems differ from one another).