Omer Dagan
Omer Dagan

Reputation: 15976

How to echo formatted string into a variable

I'm trying to accumulate formatted string in a variable. Something similar to:

for i in 1 2 3; do
    a="${a} `printf "%-10s %s" "hello" "world"`"
done

However, when I echo the output, it doesn't preserve the format, even when I use the -e or -n flags along with the echo command. How should I do that?

Thanks

Upvotes: 3

Views: 6284

Answers (1)

fedorqui
fedorqui

Reputation: 289555

Have you quoted your variable when echoing? If you do, you will see the format is kept.

$ for i in 1 2 3; do     a="${a} `printf "%-10s %s" "hello" "world"`"; done
$ echo "$a"
 hello      world hello      world hello      world

While not quoting destroys everything in the format:

$ echo $a
hello world hello world hello world

Upvotes: 8

Related Questions