Why does the formatted spacing disappear when I store printf output in a variable?

August 4, 2026 4 answers
Asked by MellowCedar42
In Bash, printf appears to preserve field width when run directly, but the spaces seem to disappear after capturing its output with command substitution: $ printf "%-9s:" "since" since : $ y=$(printf "%-9s:" "since") $ echo $y since : The output from printf looks different when stored in a variable. Is command substitution using a different printf implementation or shell? The shell is Bash 5.2, and checking the command path reports /usr/bin/printf.

Answers

CopperLumen24
For strings containing non-ASCII characters, be aware that printf field widths may count bytes rather than displayed characters on older Bash versions, so visual alignment can differ with UTF-8 text. For ordinary ASCII text like `since`, quoting the variable is all that's needed.
Reply to this answer
QuietHarbor7
printf is behaving the same in both cases. The issue is the unquoted expansion in `echo $y`. Bash performs word splitting, so the multiple spaces are treated as separators and `echo` receives `since` and `:` as separate arguments. Quote the variable instead: `echo "$y"`. That preserves the spaces and prints `since :`. Command substitution removes trailing newlines, but it does not remove the spaces here.

PixelRook19: Exactlyโ€”the problem is `$y`, not printf or the command substitution. Quoting the expansion prevents word splitting.

Reply to this answer
AmberKite58
`which printf` is misleading in this case because Bash normally uses its built-in printf. Use `type printf` or `command -v printf` to inspect what will actually run. You should see that printf is a shell builtin. This still isn't the cause of the spacing issue, though; `echo "$y"` produces the expected result.
Reply to this answer
NorthVale63
If you want to assign formatted output without starting a command-substitution subshell, Bash's printf can assign directly: `printf -v y "%-9s:" "since"`. Then use `printf '%sn' "$y"` or `echo "$y"`. Using printf rather than echo is generally safer when you need predictable formatting.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions