Karn Karn - 7 months ago 13
Bash Question

Width Specify with printf to generate a clean outlook

I have written a small snippet for nslookup on multiple hosts.., now i want to use the printf to specify the width which i am failing to implement..

What i want is to 18 char long space after any $ADDR or say Server name to have a clean display.

#!/usr/bin/sh
while read ADDR
do
RESULT=`nslookup ${ADDR}`
if [ $? != 0 ]; then
printf "%-28s\n" "Srever ${ADDR} Namelookup Failed, Please Investigate"
#echo "Server ${ADDR} Namelookup Failed, Please Investigate" | tee -a mylookup.log
else
printf "%-28s\n" "Srever ${ADDR} Namelookup Success"
#echo "Server ${ADDR} Namelookup Success" | tee -a mylookup.log
fi
done < /home/karn/host1.txt


CURRENT SCRIPT RESULT:



Srever koslfarm03.pmkrr.com Namelookup Success
Srever koslfarm04.pmkrr.com Namelookup Success
Srever koslfarm05.pmkrr.com Namelookup Success
Srever koslfarm08.pmkrr.com Namelookup Success
Srever koslfarm10 Namelookup Success
Srever koslfarm11 Namelookup Success


EXPECTED SCRIPT RESULT Should be as Below:

Srever koslfarm03.pmkrr.com Namelookup Success
Srever koslfarm04.pmkrr.com Namelookup Success
Srever koslfarm05.pmkrr.com Namelookup Success
Srever koslfarm08.pmkrr.com Namelookup Success
Srever koslfarm10 Namelookup Success
Srever koslfarm11 Namelookup Success

Answer

If you're looking for a way to create a column of specified width, use something like this:

printf 'Server %-28sNamelookup %s\n' "$ADDR" "$result"

Full script:

awk NF /home/karn/host1.txt | while read -r ADDR; do
  nslookup "$ADDR" >/dev/null

  if [ $? -eq 0 ]; then
    result="Success"
  else
    result="Failed, please investigate"
  fi

  printf 'Server %-28sNamelookup %s\n' "$ADDR" "$result"
done

Note, awk NF removes blank lines. Alternatively, you can do this within the loop:

ADDR="${ADDR// /}"
[ -z "$ADDR" ] && continue

Here we remove spaces from $ADDR, then check if the string is empty. If it's empty, we skip the iteration.

Comments