0
0
Bash Scriptingscripting~5 mins

Network monitoring script in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Network monitoring script
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: The for-loop that pings each host once.
  • How many times: Once for each host in the list.
How Execution Grows With Input

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
1010 pings
100100 pings
10001000 pings

Pattern observation: The work increases steadily and proportionally as the list of hosts grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of hosts checked.

Common Mistake

[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.

Interview Connect

Understanding how loops affect time helps you explain script efficiency clearly and shows you can think about scaling tasks.

Self-Check

"What if we changed the script to ping each host 5 times instead of once? How would the time complexity change?"