DNS lookup CLI tool (Bash + curl + jq), part of my "practice with real APIs" series

Following up on the IP/currency/WHOIS CLI tools I shared (Saturday Showcase: Built & Shared by Members This Week - #12 by Furqan_Ashraf), here’s a DNS lookup tool built the same way. Small script, real live data, good practice for parsing an actual API response instead of static test files.

Takes a domain and prints its A, AAAA, MX, NS, SOA, SPF, and TXT records in the terminal.

bash

#!/bin/bash

# dns-lookup.sh
# Usage: ./dns-lookup.sh <domain> [record_type]
# record_type: a, aaaa, mx, ns, soa, spf, txt, cname, or all (default)

API_KEY="your_api_key_here"
DOMAIN="$1"
RECORD_TYPE="${2:-all}"

if [ -z "$DOMAIN" ]; then
  echo "Usage: $0 <domain> [record_type]"
  echo "Example: $0 example.com mx"
  exit 1
fi

RESPONSE=$(curl -s -X GET \
  "https://api.apifreaks.com/v1.0/domain/dns/live?host-name=${DOMAIN}&type=${RECORD_TYPE}" \
  -H "X-apiKey: ${API_KEY}")

if ! echo "$RESPONSE" | jq empty 2>/dev/null; then
  echo "Error: unexpected response from API"
  echo "$RESPONSE"
  exit 1
fi

echo "$RESPONSE" | jq -r --arg domain "$DOMAIN" '
  if .status != true then
    "No DNS records found for \($domain)"
  else
    "Domain: \(.domainName)",
    "Registered: \(.domainRegistered)",
    "---",
    (.dnsRecords[] |
      if .dnsType == "MX" then
        "  MX\tpriority=\(.priority)\t\(.target)"
      elif .dnsType == "SOA" then
        "  SOA\thost=\(.host)\tadmin=\(.admin)\tserial=\(.serial)"
      elif .strings != null then
        "  \(.dnsType)\t\(.strings | join(" "))"
      elif .address != null then
        "  \(.dnsType)\t\(.address)"
      elif .singleName != null then
        "  \(.dnsType)\t\(.singleName)"
      else
        "  \(.dnsType)\t\(.rawText)"
      end)
  end
'

Example run:

bash

$ ./dns-lookup.sh google.com mx
Domain: google.com
Registered: true
---
  MX	priority=10	smtp.google.com.

Make it executable with chmod +x dns-lookup.sh and drop in your own API key. If anyone’s got other small Linux CLI tool ideas worth practicing with, I’d be glad to hear them.

3 Likes

Thanks for sharing this! Added to GitHub/Lab or similar?

2 Likes

Not yet, but that’s a good push to actually do it. I’ll get it up on GitHub and drop the link here once it’s up.

2 Likes