GNU/Linux >> Tutoriels Linux >  >> Linux

Bash + Utiliser Printf pour imprimer dans un format spécial ?

Je viens d'écrire le script bash suivant pour vérifier l'accès ping sur la liste des machines Linux :

for M in $list
 do
   ping -q -c 1  "$M" >/dev/null 
          if [[ $? -eq 0 ]]
   then
    echo "($C) $MACHINE CONNECTION OK"
   else
    echo "($C) $MACHINE CONNECTION FAIL"
   fi

   let C=$C+1
done

Cela imprime :

 (1) linux643 CONNECTION OK
 (2) linux72 CONNECTION OK
 (3) linux862 CONNECTION OK
 (4) linux12 CONNECTION OK
 (5) linux88 CONNECTION OK
 (6) Unix_machinetru64 CONNECTION OK

Comment puis-je utiliser printf (ou toute autre commande) dans mon script bash afin d'imprimer le format suivant ?

 (1) linux643 ............ CONNECTION OK
 (2) linux72 ............. CONNECTION OK
 (3) linux862 ............ CONNECTION OK
 (4) linux12 ............. CONNECTION OK
 (5) linux88 ............. CONNECTION FAIL
 (6) Unix_machinetru64 ... CONNECTION OK

Réponse acceptée :

Utilisation de l'expansion des paramètres pour remplacer les espaces résultant de %-s par points :

#!/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

Linux
  1. Utilisation de Bash pour l'automatisation

  2. Bash Convertir \xc3\x89 en É ?

  3. Utilisation de la commande Linux Sleep dans les scripts Bash

  4. Bash Beginner Series #9 :Utiliser des fonctions dans Bash

  5. Utilisation des déclarations de cas dans Bash

Bash printf - Comment imprimer une variable dans Bash

Commande Bash printf

Ssh – Vous utilisez un canal Ssh déjà établi ?

Utilisation de la commande Bash printf pour imprimer des sorties formatées

Utilisation de Bash Sort pour trier les fichiers comme un patron

Afficher chaque taille de sous-répertoire dans un format de liste à l'aide d'une commande de ligne dans Bash ?