bash + using printf in order to print in special format

Using parameter expansion to replace spaces resulting from %-s by dots:

#!/bin/bash
list=(localhost google.com nowhere)
C=1
for M in "${list[@]}"
do
    machine_indented=$(printf '%-20s' "$M")
    machine_indented=${machine_indented// /.}

    if ping -q -c 1  "$M" &>/dev/null ;  then
        printf "(%2d) %s CONNECTION OK\n" "$C" "$machine_indented"
    else
        printf "(%2d) %s CONNECTION FAIL\n" "$C" "$machine_indented"
    fi
    ((C=C+1))
done

for m in $list is zsh syntax. In bash it would be for i in "${list[@]}".

bash doesn't have padding operators. You can do padding with printf but only with spaces, not arbitrary characters. zsh has padding operators.

#! /bin/zsh -
list=(
  linux643
  linux72
  linux862
  linux12
  linux88
  Unix_machinetru64
)
c=0
for machine in $list; do
  if ping -q -c 1 $machine >& /dev/null; then
    state=OK
  else
    state=FAIL
  fi
  printf '%4s %s\n' "($((++c)))" "${(r:25::.:):-$machine } CONNECTION $state"
done

The padding operator is ${(r:25:)parameter} to right-pad with length 25 with spaces or ${(r:25::string:)parameter} to right-pad with any string instead of space.

We also use printf '%4s' to left-pad the (x) with spaces. We could have used ${(l:4:):-"($((++c)))"} instead. A notable difference though is that if the string is more than 4 characters long, ${(l)} would truncate it, while it would overflow with printf.


The %s format specifier can take a precision (%.20s for example), and just as when you want to output a float value to a certain precision (with %.4f for example), the output will be at most that many characters from the given string argument.

So create a string that contains the machine name and enough dots to run out of dots:

cnt=0
for hname in vboxhost ntp.stupi.se example.com nonexistant; do
   if ping -q -c 1  "$hname" >/dev/null 2>&1; then
       status="OK"
   else
       status="FAIL"
   fi

   printf "(%d) %.20s CONNECTION %s\n" \
       "$(( ++cnt ))" "$hname ...................." "$status"

done

Output:

(1) vboxhost ........... CONNECTION OK
(2) ntp.stupi.se ....... CONNECTION OK
(3) example.com ........ CONNECTION OK
(4) nonexistant ........ CONNECTION FAIL