bash heredoc — write multiline strings

# Basic heredoc
cat <<EOF
Line one
Line two with variable: $USER
EOF

# Write to a file
cat <<EOF > config.yml
database:
  host: localhost
  port: 5432
EOF

You need to write a multiline string in a script without a separate template file.

Indented heredoc (<<-)

<<- strips leading tabs (not spaces) from each line, so the heredoc can be indented with the surrounding code.

if true; then
	cat <<-EOF
		This line has tabs stripped
		So does this one
	EOF
fi

Disable variable expansion (quoted delimiter)

# Single-quote the delimiter to treat content as literal text
cat <<'EOF'
No expansion: $USER  \n  $(date)
EOF
# prints literally: No expansion: $USER  \n  $(date)

Pass heredoc as stdin to a command

# Send SQL to psql
psql -U postgres <<EOF
CREATE DATABASE myapp;
GRANT ALL PRIVILEGES ON DATABASE myapp TO appuser;
EOF

# SSH remote commands
ssh user@host <<'ENDSSH'
cd /app && git pull && npm run build
ENDSSH

Herestring — single-line stdin

# <<< passes a string as stdin
grep "pattern" <<< "some text with pattern here"

# Useful to avoid echo | command
base64 <<< "hello world"