Why network scripts automate connectivity tasks in Bash Scripting - Performance Analysis
We want to see how the time needed to run network scripts changes as the tasks grow.
How does running commands repeatedly affect the total time?
Analyze the time complexity of the following code snippet.
#!/bin/bash
hosts=("192.168.1.1" "192.168.1.2" "192.168.1.3" "192.168.1.4")
for host in "${hosts[@]}"; do
ping -c 1 "$host" >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "$host is reachable"
else
echo "$host is unreachable"
fi
done
This script checks if each host in a list is reachable by sending one ping.
- 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 ping command, so the total work grows steadily with the number of hosts.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 ping commands |
| 100 | 100 ping commands |
| 1000 | 1000 ping commands |
Pattern observation: The time grows directly with the number of hosts checked.
Time Complexity: O(n)
This means the time to finish grows in a straight line as you add more hosts.
[X] Wrong: "Running the script once checks all hosts instantly."
[OK] Correct: Each host requires its own ping command, so time adds up with more hosts.
Understanding how scripts scale with input size helps you write efficient automation and explain your approach clearly.
"What if we ping multiple hosts in parallel instead of one by one? How would the time complexity change?"