How to create a Bash script to get the registrar name from the whois command

How to create a Bash script to get the registrar name from the whois command

In this article, I will walk you through the process of creating a Bash script to specifically extract the Registrar name from the whois command output.

Using the whois command is a common task for getting detailed information about domains, such as the registration date, expiration date, registrant details, and the registrar itself. In this article, I will walk you through the process of creating a Bash script to specifically extract the Registrar name from the whois command output.

Let's create a new file called extract_registrar.sh.


touch extract_registrar.sh
chmod +x extract_registrar.sh

Then add the following content to the file. This script takes a domain name as an argument, runs the whois command, and uses grep and awk to extract the Registrar name.


#!/bin/bash

# Check if an argument was passed
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 domain_name"
    exit 1
fi

# Run the whois command and extract the Registrar
whois_output=$(whois "$1")

if [[ $? -ne 0 ]]; then
    echo "Error executing whois command"
    exit 1
fi

# Extract Registrar from whois output
registrar=$(echo "$whois_output" | grep -i "Registrar:" | awk -F: '{print $2}' | sed 's/^ *//; s/ *$//')

# Check if registrar was found
if [ -z "$registrar" ]; then
    echo "Cannot find Registrar for domain $1"
else
    echo "Registrar for domain $1 is: $registrar"
fi

In detail:

  • Checking arguments: The first part of the script checks if a domain name was passed as an argument. If not, it displays an error message and exits.

  • Running the whois command: The script runs the whois command to get the domain information. If whois returns an error, the script reports it and exits.

  • Extracting the Registrar: Using grep, awk and sed, the script searches for the line containing "Registrar:", extracts the registrar name and removes any extra spaces.

  • Verifying the result: Finally, the script checks whether the registrar name was found and prints it. If the name is not found, it prints an error message.

Conclusion

We have created a simple but effective Bash script to extract the Registrar name from the output of the whois command. This tool can be useful for anyone who needs to manage or monitor multiple domains and wants to automate the collection of specific information. With a few basic commands and tools like grep, awk and sed, you can build powerful scripts to automate network and system administration tasks.