How to use here documents and here strings in bash
· Category: Linux
Short answer
Here documents (<<EOF) and here strings (<<<) pass text directly into a command's stdin.
Steps
- Here document:
cat <<EOF
Line 1
Line 2
EOF
- Here string:
grep "word" <<< "this is a word test"
- Disable variable expansion:
cat <<'EOF'
Literal $VAR
EOF
Tips
- Indent EOF with tabs by using
<<-EOF. - Here documents are great for embedding SQL or config files in scripts.
- Here strings avoid creating temporary files for simple input.
Common issues
- Leading spaces on the closing delimiter prevent recognition.
- Variable expansion happens by default; quote the delimiter to disable.