I am trying to create a table in bash - I have collected all headings into a var - however when I print these strings enclosed in "'s are treated as new columns and not as one by the printf command

When I pass the same values directly it works fine, but I get different behavior when I use $var instead.

$ printf '%-20s' "some spaced words" other values; echo -e "\n"
some spaced words   other               values

$ values='"some spaced words" other values'
$ echo $values
"some spaced words" other values
$ printf '%-20s' $values; echo -e "\n"
"some               spaced              words"              other               values

I'm clearly misunderstanding something about how my variable is different to < some string > and therefore results in the different behavior.

How do I get the output that matches output 1 when using a variable?

edit: I can see the var version has the quotes - is there a way I can pass quoted strings to printf as a variable?

  • You problem is that $values expand the contents of values into a word list: so the echo and printf are both getting a modified version of the variable. Always quote variable expansions! If you want to see what is really in a variable or array, use declare -p values. Oct 2, 2020 at 12:31
  • Yes, part of my problem was I wasn't even passing the string I thought I was. Also I did try quoting {}'s etc and wasn't able to produce the output I wanted
    – bob dylan
    Oct 2, 2020 at 12:35

1 Answer 1


Variable is expanded before the shell runs any command, i.e. printf here, and word splitting happens after variable expansion. Use an array instead of a scalar variable:

values=('some spaced words' other values)
printf %-20s "${values[@]}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .