I am writing a bash shell script to display if a process is running or not.
So far, I got this:
printf "%-50s %s\n" $PROC_NAME [UP]
The code gives me this output:
JBoss [DOWN]
GlassFish [UP]
verylongprocessname [UP]
I want to pad the gap between the two fields with a '-' or '*' to make it more readable. How do I do that without disturbing the alignment of the fields?
The output I want is:
JBoss ------------------------------------------- [DOWN]
GlassFish --------------------------------------- [UP]
verylongprocessname ----------------------------- [UP]
There's no way to pad with anything but spaces using
printf
. You can usesed
:using
echo
onlyThe anwser of @Dennis Williamson is working just fine except I was trying to do this using echo. Echo allows to output charcacters with a certain color. Using printf would remove that coloring and print unreadable characters. Here's the
echo
-only alternative:output:
of course you can use all the variations proposed by @Dennis Williamson whether you want the right part to be left- or right-aligned (replacing
25 - ${#string1}
by25 - ${#string1} - ${#string2}
etc...Here's another one:
I think this is the simplest solution. Pure shell builtins, no inline math. It borrows from previous answers.
Just substrings and the ${#...} meta-variable.
Produces
Produces
If you are ending the pad characters at some fixed column number, then you can overpad and
cut
to length:Bash + seq to allow parameter expansion
Similar to @Dennis Williamson answer, but if
seq
is available, the length of the pad string need not be hardcoded. The following code allows for passing a variable to the script as a positional parameter:The ASCII code "2D" is used instead of the character "-" to avoid the shell interpreting it as a command flag. Another option is "3D" to use "=".
In absence of any padlength passed as an argument, the code above defaults to the 80 character standard terminal width.
To take advantage of the the bash shell variable
COLUMNS
(i.e., the width of the current terminal), the environment variable would need to be available to the script. One way is to source all the environment variables by executing the script preceded by.
("dot" command), like this:or (better) explicitly pass the
COLUMNS
variable when executing, like this: