Network monitoring script in Bash Scripting - Time & Space Complexity
We want to understand how the time needed to run a network monitoring script changes as we check more hosts.
How does the script's work grow when the list of hosts gets bigger?
Analyze the time complexity of the following code snippet.
#!/bin/bash
hosts=("192.168.1.1" "192.168.1.2" "192.168.1.3")
for host in "${hosts[@]}"; do
ping -c 1 "$host" >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "$host is up"
else
echo "$host is down"
fi
done
This script checks if each host in the list is reachable by sending one ping and then prints if it is up or down.
- Primary operation: The for-loop that pings each host once.
- How many times: Once for each host in the list.
Each new host adds one more ping command to run, so the total work grows directly with the number of hosts.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 pings |
| 100 | 100 pings |
| 1000 | 1000 pings |
Pattern observation: The work increases steadily and proportionally as the list of hosts grows.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of hosts checked.
[X] Wrong: "The script runs in constant time because each ping is quick."
[OK] Correct: Even if one ping is fast, the script runs one ping per host, so more hosts mean more total time.
Understanding how loops affect time helps you explain script efficiency clearly and shows you can think about scaling tasks.
"What if we changed the script to ping each host 5 times instead of once? How would the time complexity change?"