brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a quoted EOF stops the shell from expanding a here-document

Shell
~/tips/tip-shell-quoted-heredoc

EOF

Write a script or config with dollar signs from a here-document, untouched.

A here-document is the easiest way to write a small file from a script. By default the shell expands every $ and backtick inside it, which is a problem when the text you write is itself a script.

Quote the word after << and nothing inside gets expanded:

cat <<'EOF' > /usr/local/bin/cleanup.sh
#!/bin/sh
find "$1" -name '*.tmp' -delete
echo "done at $(date)"
EOF

The file now contains $1 and $(date) literally, which is what the new script needs. Without the quotes, $1 would have been replaced by the first argument of the script that writes the file, probably an empty string, and $(date) by the time of writing.

It does not matter which quote you use or where: 'EOF', "EOF" and \EOF all switch expansion off. The closing line stays a bare EOF without quotes.

If you need a mix, leave the word unquoted and escape only the dollars you want to keep, like \$1. I find that harder to read than two separate here-documents. And watch the closing word: it has to sit alone on its line, with no spaces after it, or the shell keeps reading until the end of the file.

Further reading: Bash manual: Here Documents

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link