Here Documents and Strings
Uses here documents and here strings to feed multi-line text to commands, generate config files, and create inline data for script processing.
Code
#!/usr/bin/env bash
set -euo pipefail
# Here document: no expansion (quoted delimiter)
cat > /tmp/config.yaml << 'EOF'
server:
host: localhost
port: 8080
timeout: 30
database:
url: postgres://localhost:5432/mydb
pool_size: 10
logging:
level: info
file: /var/log/app.log
EOF
echo "Config file created"
# Here document: with variable expansion
app_name="MyApp"
version="1.0.0"
cat > /tmp/app.info << EOF
Application: $app_name
Version: $version
Generated: $(date +%Y-%m-%d)
PID: $$
EOF
cat /tmp/app.info
# Here string (single line)
read -r first second third <<< "one two three"
echo "Parsed: $first / $second / $third"
# Here document to function
process_data() {
while IFS= read -r line; do
echo " > $line"
done
}
process_data << EOF
Line 1: Hello
Line 2: World
Line 3: From Bash
EOF
# Generate script from heredoc
cat > /tmp/generated.sh << 'SCRIPT'
#!/usr/bin/env bash
echo "Generated script running"
echo "Arguments: $@"
SCRIPT
chmod +x /tmp/generated.sh
/tmp/generated.sh arg1 arg2
# Cleanup
rm -f /tmp/config.yaml /tmp/app.info /tmp/generated.shReport a problem with this exampleOpens a pre-filled issue on GitHub.