Sagar.BlogArticle
All posts
All posts
Bash

Formatted Output with printf

printf gives you precise control over output formatting — column alignment, fixed decimal places, padding, and special characters. Learn when printf beats echo.

January 21, 20265 min read
BashprintfOutputScripting

echo is fine for simple output, but printf gives you control. It works like C's printf: a format string with placeholders, followed by values. No automatic newline. Cross-platform consistent.

printf vs echo

When to use printf over echo

SituationUse
Simple string outputecho
Formatted numbers/columnsprintf
Strings with special charactersprintf
Cross-platform portabilityprintf
Newline controlprintf (echo -e is non-portable)

Format Specifiers

# %s — string
printf "%s\n" "hello"             # hello

# %d — decimal integer
printf "%d\n" 42                  # 42

# %f — floating-point
printf "%.2f\n" 3.14159           # 3.14  (2 decimal places)
printf "%8.2f\n" 3.14159          # "    3.14" (8 wide, 2 decimal)

# %05d — zero-padded integer
printf "%05d\n" 42                # 00042

# %-20s — left-aligned string in 20-char field
printf "%-20s %s\n" "Name:" "Alice"

# %b — string with backslash escapes (like echo -e)
printf "%b" "Line1\nLine2\n"     # interprets 
 as newline

# Multiple values — format repeats
printf "%s\n" apple banana cherry
# apple
# banana
# cherry

Tabular Output

#!/usr/bin/env bash
# Print a nicely aligned table

printf "%-15s %-10s %8s\n" "NAME" "STATUS" "SIZE"
printf "%-15s %-10s %8s\n" "----" "------" "----"

while IFS= read -r line; do
    name=$(echo "$line" | awk '{print $1}')
    status="active"
    size=$(du -sh "$line" 2>/dev/null | cut -f1)
    printf "%-15s %-10s %8s\n" "$name" "$status" "${size:-N/A}"
done < <(find /etc -maxdepth 1 -name "*.conf" | head -5)

printf for Building Strings

# Store formatted output in variable
formatted=$(printf "%-10s = %05d" "count" 42)
echo "$formatted"      # count      = 00042

# Hex output
printf "%x\n" 255     # ff
printf "%X\n" 255     # FF
printf "0x%08X\n" 255 # 0x000000FF

# Character output
printf "%c\n" 65      # A  (ASCII 65)
Quick Check

What does `printf "%-10s|%10s\n" "left" "right"` output?

Exercise

Write a script that prints a currency report. Given an array of items and prices, print:

  • A header row: "ITEM PRICE"
  • Each item left-aligned in 17 chars, price right-aligned as $XX.XX
  • A total at the bottom

Example items: ("Coffee" 2.5 "Sandwich" 8.99 "Water" 1.25)