EGr
EGr

Reputation: 2172

Printf is adding newlines in BASH, and I'm not sure how to get rid of them

I have the following printf statement in my BASH script to show my script's output nicely:

printf "%-20s %-25s %-5s %-10s %-20s \n" $hostn $kernl $uptim $owner $team

The output from this is the following:

Hostname1        2.6.32.12-0.7-default     307   Lastname, Firstname
Team1
Hostname2        2.6.32.12-0.7-default     270   Lastname, Firstname
Team1
Hostname3        2.6.32.12-0.7-default     298   Lastname, Firstname
Team1
Hostname4        2.6.32.12-0.7-default     271   Lastname, Firstname
Team2

I'm not sure why the Team is being added to a new line. I've tried adding another field but it does the same thing:

printf "%-20s %-25s %-5s %-10s %-20s %s\n" $hostn $kernl $uptim $owner $team "test"

Hostname1        2.6.32.12-0.7-default     307   Lastname, Firstname         Team1
test
Hostname2        2.6.32.12-0.7-default     270   Lastname, Firstname         Team1
test
Hostname3        2.6.32.12-0.7-default     298   Lastname, Firstname         Team1
test
Hostname4        2.6.32.12-0.7-default     271   Lastname, Firstname         Team2
test

Where are these newlines coming from? Is my printf formatting incorrect?

Upvotes: 1

Views: 167

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295373

Always quote your expansions (all of them, unless you have a specific reason for doing otherwise!) when writing shell scripts:

printf "%-20s %-25s %-5s %-10s %-20s %s\n" \
       "$hostn" "$kernl" "$uptim" "$owner" "$team" "test"

Since your $owner can contain whitespace, if you don't quote correctly, the last name can slip over into the $team field otherwise -- and the test thus shows up as another %-20s field meant for the next line's $hostn.

Upvotes: 3

Related Questions