0
0
Bash Scriptingscripting~5 mins

Service health check script in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Service health check script
O(n)
Understanding Time Complexity

When running a service health check script, it's important to know how the time it takes grows as you check more services.

We want to understand how the script's work increases when the number of services grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


services=("nginx" "mysql" "redis" "docker")

for service in "${services[@]}"; do
  systemctl is-active --quiet "$service"
  if [ $? -eq 0 ]; then
    echo "$service is running"
  else
    echo "$service is NOT running"
  fi
 done
    

This script checks if each service in the list is running and prints its status.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each service to check its status.
  • How many times: Once for each service in the list.
How Execution Grows With Input

As the number of services increases, the script runs the check for each one separately.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of operations grows directly with the number of services.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the script grows in a straight line as you add more services to check.

Common Mistake

[X] Wrong: "The script runs in the same time no matter how many services are checked."

[OK] Correct: Each service requires a separate check, so more services mean more work and more time.

Interview Connect

Understanding how loops affect script time helps you write efficient checks and explain your reasoning clearly in interviews.

Self-Check

"What if we added nested loops to check multiple properties per service? How would the time complexity change?"