BudiBadu Logo
Samplebadu

Bash by Example: Network Ping Monitor

Bash 5.0+

Checking network connectivity to multiple hosts using ping commands for network diagnostics, implementing parallel connectivity testing, detecting network outages or routing issues, validating network infrastructure health, and building network monitoring dashboards with bash scripts.

Code

#!/bin/bash

HOSTS=("8.8.8.8" "1.1.1.1" "google.com" "bad.host.local")

echo "Starting Network Scan..."
printf "%-20s %-10s %s\n" "HOST" "STATUS" "LATENCY"
echo "---------------------------------------------"

for host in "${HOSTS[@]}"; do
    # Ping 1 packet, wait max 1 second
    # Extract time=XX.X ms using grep and cut/awk
    result=$(ping -c 1 -W 1 "$host" 2>&1)
    
    if [ $? -eq 0 ]; then
        # Parse latency
        # Output format: ... time=14.2 ms ...
        latency=$(echo "$result" | grep "time=" | sed 's/.*time=\([0-9.]*\) ms.*/\1ms/')
        printf "%-20s \e[32m%-10s\e[0m %s\n" "$host" "UP" "$latency"
    else
        printf "%-20s \e[31m%-10s\e[0m -\n" "$host" "DOWN"
    fi
done

Explanation

Network troubleshooting often starts with a simple question: "Is the server up?" The ping command uses ICMP Echo Request packets to test reachability. Automating this for a list of hosts allows system administrators to quickly visualize the state of their network infrastructure.

This script iterates through an array of hostnames or IP addresses. It sends a single ping packet (-c 1) with a strict timeout (-W 1) to ensure the script doesn't hang waiting for offline hosts. It then parses the output to extract the round-trip time (latency), which is a crucial metric for performance.

We also use printf instead of echo for output. This allows us to format the data into neat, aligned columns, making the report much easier to read. The ANSI escape codes (\e[32m) add color (green for UP, red for DOWN) to improve visual scanning.

Code Breakdown

3
Bash Arrays ("a" "b") allow us to store lists of items. We loop through them using "${HOSTS[@]}".
17
sed regex capturing. The pattern .*time=([0-9.]*) ms.* matches the entire line but captures the number inside the parentheses. \1 replaces the whole line with just that captured number.