Bash

Pad String to Fixed Width

admin by @admin ADMIN
38m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Pad strings left or right so columnar output lines up. printf gets you about 95% of what you need; the helpers wrap it for readability.
Bash
Raw
padr() { printf '%-*s' "$2" "$1"; }       # right-pad (left-align)
padl() { printf '%*s'  "$2" "$1"; }       # left-pad (right-align)

# Examples:
padr "alice" 12      # "alice       "
padl "alice" 12      # "       alice"

# Real-world: aligned table
printf '%-12s %5s\n' "USER" "JOBS"
for user in alice bob charlie dave; do
    printf '%-12s %5d\n' "$user" $RANDOM
done
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.