Hey everyone,
Today I want to share a simple little shell script that I've found surprisingly useful over the years. A while back, I came across a post on Reddit where someone was asking for an easy way to ping a list of servers to find the one with the fastest response time. I whipped up a quick script to solve the problem, and I've honestly ended up using it far more than I ever expected.
I call it pinger.sh
, and its job is simple: it takes a file full of IP addresses or domain names, pings each one, and gives you a nicely formatted, sorted list of the results from fastest to slowest.
It's perfect for a couple of common tasks:
- Doing a quick uptime check on a list of your personal servers.
- Finding the fastest software mirror or public DNS server from your specific location.
Examples in Action
For instance, I can use it to get a quick status update on my personal servers to make sure everything is running smoothly:
Or, I can use it to quickly find the fastest public DNS resolver from my current location:
The Script
The script itself is a short and straightforward Bash script. It reads each line from the file you provide, pings the address once, and then uses a powerful sort | column
pipeline at the end to format everything into a neat, easy-to-read table.
#!/bin/bash
# Check if the argument is provided
if [ $# -eq 0 ]; then
echo "Please provide a filename as an argument."
exit 1
fi
# Read each line of the file
while read -r address; do
# setting timeout, piping error
# Execute ping; if it fails, skip to the next address
result=$(ping -c 1 -W 2 "$address" 2>/dev/null) || continue
# Extract the ping time from the result using cut
time=$(echo "$result" | grep "time=" | cut -d "=" -f 4)
# Print the address and the ping time
echo "$address $time"
done <"$1" | sort -k 2n | column -t -N "Address,Speed"
How to Use It
- Save the code above to a file named
pinger.sh
. - Make the script executable from your terminal:
chmod +x pinger.sh
- Create a text file (e.g.,
servers.txt
) with one IP address or domain name per line. - Run the script and pass it your text file as an argument:
./pinger.sh servers.txt
It's a simple tool, but it's a great example of how a small script can solve a common problem in a very elegant way.
As always,
Michael Garcia a.k.a. TheCrazyGM