How to pad spaces of a certain width in a echo based output

Viewed 130

I would like to take expert advice to pad spaces of a certain width in an echo based output as I have below to make sure that the Columns are delimited with correct whitespace so, table output is useful for pretty-printing

Below is Just an echo statement of a code:

if [[ $? -eq 0 ]]
then
    echo -e  "$CurrntTime $MachineName   : SSH connection is Up"
elif [[ $? -eq 255 ]]
    then
    echo -e "$CurrntTime $MachineName   : SSH Authentication Failed"

Produced Output:

Below output as you see little distorted.

02/17/2021 23:56:15 myserver001   : SSH connection is Up
02/17/2021 23:56:15 myserver00101   : SSH connection is Up

Desired Output:

02/17/2021 23:56:15 myserver001     : SSH connection is Up
02/17/2021 23:56:15 myserver00101   : SSH connection is Up
1 Answers

Converting my comment to answer so that solution is easy to find for future visitors.

You may try this printf with width=25 for 2nd field and - for left alignment:

printf "%s %-25s : %s\n" "$CurrntTime" "$MachineName" "SSH connection is Up"

# or
printf "%s %-25s : %s\n" "$CurrntTime" "$MachineName" "SSH Authentication Failed"
Related