Bash Tutorial · Bash Scripting · Lesson 23 of 30
Bash Here Documents and printf
Write multi-line text with here-documents and format output reliably with printf.
Here-documents
<<EOF ... EOF feeds multiple lines to a command. With <<'EOF' (quoted) nothing inside is expanded; with
<<EOF variables are. <<-EOF strips leading tabs.
app=shop; port=8080
cat > app.env <<EOF
APP_NAME=$app
APP_PORT=$port
EOF
cat app.env
cat <<'EOF'
Literal: $app is not expanded here
EOF
Output
APP_NAME=shop APP_PORT=8080 Literal: $app is not expanded here
Run this on your computer — see “Get Started” for setup.
printf
printf is more predictable than echo for formatting: %s string, %d integer, %.2f decimal, %-10s
left-aligned width.
printf '%-8s %6s\n' NAME ORDERS
printf '%-8s %6d\n' Ana 12 Ben 3 Chen 7
printf 'total: %.2f EUR\n' 41.5
Output
NAME ORDERS Ana 12 Ben 3 Chen 7 total: 41.50 EUR
Run this on your computer — see “Get Started” for setup.
Test yourself
What's the difference between <<EOF and <<'EOF'?
NoneWith quotes, variables inside are not expandedQuotes make it a commentQuotes allow tabs
Show answer
Answer: With quotes, variables inside are not expanded