Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm echoing some text in a bash script with a variable in it, and want to pad that variable so it will always have the appropriate ammount of spaces to the right to keep the rest of the text aligned.

Here's an example of what I want:

Echoing random number 1080    [ OK ] Echoing random number 443     [ OK ] Echoing random number 34842   [ OK ] 

The numerical value would be of varying length (probably no longer than 5 or 6 digits).

I know that printf can do this and right align the variable by doing the following:

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

However, this would format the text like this:

Echoing random number  1080   [ OK ] Echoing random number   443   [ OK ] Echoing random number 34842   [ OK ] 

And of course just echoing with spaces doens't work:

echo "Echoing random number ${RAND_NUM}   [ OK ]" 

Produces this:

Echoing random number 1080   [ OK ] Echoing random number 443   [ OK ] Echoing random number 34842   [ OK ] 

Is there a way to print the text like my first example?

like image 861
PHLAK Avatar asked Jun 14 '11 14:06

PHLAK


People also ask

What does %% mean in bash?

The operator "%" will try to remove the shortest text matching the pattern, while "%%" tries to do it with the longest text matching.

How do I print text in bash?

Print String in Bash To print a string in Bash, use echo command. Provide the string as command line argument to echo command.

What is whitespace in Bash?

Whitespace — this is a tab, newline, vertical tab, form feed, carriage return, or space. Bash uses whitespace to determine where words begin and end. The first word is the command name and additional words become arguments to that command.


1 Answers

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 
like image 54
John Kugelman Avatar answered Sep 20 '22 12:09

John Kugelman