2

Why is the output of these two different? I want the spaces to be preserved.

#!/bin/bash

x="foo"
printf "%-12s *" $x

echo " "

y=$(printf "%-12s" $x)
echo $y "*"

Running it gives

foo          *
foo *

I want the second line to look like the first.

Carl Whalley
  • 3,011
  • 8
  • 33
  • 48
  • 1
    `printf` does preserve the spaces -- its the `echo` that's removing them (when unquoted). Try `echo "$y *"` instead. – costaparas Dec 29 '20 at 00:39
  • Very closely related to [Capturing multiple line output into a Bash variable](https://stackoverflow.com/a/613580/15168) — the basic answer is "quote variables used in argument lists" (almost always — absolutely always if the spacing matters). – Jonathan Leffler Dec 29 '20 at 01:01

2 Answers2

2

You'll need to quote the $y:

echo "${y} *"
#!/bin/bash

x="foo"
printf "%-12s *" $x

echo " "

y=$(printf "%-12s" $x)
echo "$y" "*"
➜ ./test.sh
foo          *
foo          *
➜ 

More information about when to use double quotes

0stone0
  • 34,288
  • 4
  • 39
  • 64
0

Ypu can use printf too

printf '%s *\n' "$y"
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134