Home > Enterprise >  bash script to append result next to value in list
bash script to append result next to value in list

Time:09-02

So I have a simple bash script that executes a whois command of a domain list.

list.txt
domain1.com
domian2.com
domain3.net

.... (there are more than 200 values)

This returns the Registar URL. In some cases this is null and in some others it returns a real value. But I would like to know exactly the value and append that next to heach of the values of the list is this possible? Would like the result to be:

list.txt
domain1.com godaddy.com
domian2.com godaddy.com
domain3.net NULL

This is script but it only returns value and i´m not sure if they match with the array of values in the list. I also did similar with for each but I think while loop is better? Is there a different way to do it?

while read p; do
      whois "$p" | grep 'Registrar URL' | awk '{print $3}' || true
      if [ ! -z "$p" ]
       then
          echo "\$p is empty"
      else
          echo "\$p is NOT empty"
    fi
    
    done < list.txt

CodePudding user response:

You weren't far from the mark.

#!/usr/bin/env bash
while IFS= read -r p; do
    result=$(whois "$p" | awk '/Registrar URL/ {print $3}')
    printf '%s\t%s\n' "$p" "${result:-NULL}"
done <list.txt
  • Using the -r argument to read prevents backslashes in the input from being silently removed.
  • Using awk '/pattern/ { action }' avoids the need for a separate grep.
  • Using var=$(pipeline) stores the output of your pipeline in a variable so you can operate on its results.
  • ${var:-value} is a parameter expansion that expands to $var should the variable be set and non-empty, or to the constant value "value" otherwise.
  • Related