0

I am working at my first script. I want to use dig to get query time for multiple sites from a .txt file and print the average. Here's the source, I don't know how to print only query time without text. Thanks!

#!/bin/bash

# Colors
default='\033[0m'    # Default
red='\033[0;31m'     # Red
green='\033[0;32m'   # Green
blue='\033[0;34m'    # Blue
cyan='\033[0;36m'    # Cyan

# Vars / const
options='+nocomments +stats'
sites="$(cat sites.txt)"

# User input
echo -ne "${blue}Please enter DNS server: $default"
read dns

echo -e "${green}Welcome to main menu!"
echo -ne "${green}(0) ${default}- Default list / ${green}(1)${default} Custom / ${green}(3)${default} - Install dependencies ${default}: "
read choose


# Conditions for $choose

if [ "$choose" == "0" ]; then
    echo -e "${cyan}"
    /usr/bin/dig @$dns ${options} ${sites}
    echo -e "${default}"

elif [ "$choose" == "1" ]; then
    echo -ne "${blue}Please write the sites here. ${default}Example: ${blue}( google.com instagram.com ) : ${default}"
    read custom_list
    echo -e "${cyan}"
    /usr/bin/dig @$dns ${options} $custom_list
    echo -e "${default}"

elif [ "$choose" == "3" ]; then
apt-get install -y dnsutils



else
echo -e "${blue}Please choose ${default}(0) ${blue}or ${default}(1)"
fi
Corion
  • 3,855
  • 1
  • 17
  • 27
Aly x
  • 1
  • 2

1 Answers1

0

You can pipe dig to awk to calculate the average:

/usr/bin/dig @$dns ${options} $custom_list | 
    awk '/Query time/ { total += $4; count++ } 
         END {print "Average:", total/count, "ms" }'

The lines with the query times look like:

;; Query time: 61 msec

So this matches the string Query time, adds the 4th field to the total variable and increments a counter. At the end, it divides the total by the count to calculate the average.

Barmar
  • 741,623
  • 53
  • 500
  • 612