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

0
0
Asked By MellowCedar42 On

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.

4 Answers

Answered By NorthVale63 On

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.

Answered By AmberKite58 On

`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.

Answered By QuietHarbor7 On

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.

Answered By CopperLumen24 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.