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.shHere documents (<< DELIMITER) feed multi-line text to commands. Quoted delimiters (<< 'EOF') prevent expansion; unquoted allow variable and command expansion. <<- strips leading tabs for indented heredocs. Here strings (<<<) feed single-line input. Heredocs are useful for generating config files, inline scripts, SQL queries, and feeding data to functions.
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
Report a problem with this exampleOpens a pre-filled issue on GitHub.