How do I print some text in bash and pad it with spaces to a certain width?

Solution 1:

Use - to left align a field.

printf "Echoing random number %-5s   [ OK ]" $RAND_NUM

Alternatively, if you're on a Red Hat Linux system there are predefined functions that will print out green OK and red FAILED prompts (the ones you see during bootup):

#!/bin/bash

. /etc/init.d/functions

echo -n "Frobbing widget:"
frob_widget && echo_success || echo_failure
echo

Solution 2:

Collect all your lines in one var or text file then pipe it through column command. So this (my example file /tmp/columns.txt)

Echoing random number 1080 [ OK ]
Echoing random number 44332356 [ OK ]
Echoing random number 34842 [ OK ]
Echoing random number 342 [ OK ]

became this

Echoing  random  number  1080      [  OK  ]
Echoing  random  number  44332356  [  OK  ]
Echoing  random  number  34842     [  OK  ]
Echoing  random  number  342       [  OK  ]

Example command: cat /tmp/columns.txt | column -t

Solution 3:

To expand on sobi3ch's answer: if you concat the strings with a deliminator (I use tilda (~)), you can then call column with the -s param to split the text at that point.

Apologies for the feline abuse:

foo.txt :

Echoing random number 1080~[ OK ]
Echoing random number 1080~[ OK ]
Echoing random number 1080~[ Failed ]

then :

cat foo.txt | column -s'~'

Echoing random number 1080        [ OK ]
Echoing random number 1080        [ OK ]
Echoing random number 1080        [ Failed ]