Service health check script in Bash Scripting - Time & Space 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.
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 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.
As the number of services increases, the script runs the check for each one separately.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows directly with the number of services.
Time Complexity: O(n)
This means the time to run the script grows in a straight line as you add more services to check.
[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.
Understanding how loops affect script time helps you write efficient checks and explain your reasoning clearly in interviews.
"What if we added nested loops to check multiple properties per service? How would the time complexity change?"