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.

Create a free account to save this page, take notes and track your progress. Sign in

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.

Generating a config file
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.

Aligned output with printf
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'?

  1. None
  2. With quotes, variables inside are not expanded
  3. Quotes make it a comment
  4. Quotes allow tabs
Show answer

Answer: With quotes, variables inside are not expanded

Was this page helpful?