0
0
Bash Scriptingscripting~5 mins

Disk space monitoring script in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Disk space monitoring script
O(n^2)
Understanding Time Complexity

We want to understand how the time to run a disk space monitoring script changes as the number of disks or partitions grows.

Specifically, how does the script's work increase when checking more disk entries?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

#!/bin/bash

# Check disk usage for all mounted filesystems
for disk in $(df -h | tail -n +2 | awk '{print $1}'); do
  usage=$(df -h | grep "^$disk" | awk '{print $5}' | sed 's/%//')
  if [ "$usage" -gt 80 ]; then
    echo "Warning: Disk $disk is $usage% full"
  fi
done

This script loops through each disk or partition, checks its usage percentage, and warns if usage is above 80%.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over each disk entry from the disk list.
  • How many times: Once for each disk or partition found by df.
  • Inside the loop: Running df and grep commands again for each disk.
How Execution Grows With Input

As the number of disks (n) increases, the script runs the loop n times, with each iteration running df -h (O(n)) and grep (O(n)) over all n entries.

Input Size (n)Approx. Operations
10About 10 loops × ~10 ops each = ~100 total
100About 100 loops × ~100 ops each = ~10,000 total
1000About 1000 loops × ~1000 ops each = ~1,000,000 total

Pattern observation: The total work grows roughly in proportion to the square of the number of disks.

Final Time Complexity

Time Complexity: O(n^2)

This means the script's running time grows quadratically as the number of disks increases.

Common Mistake

[X] Wrong: "The script runs in constant time because it just checks disk usage once."

[OK] Correct: The script actually loops over each disk, so more disks mean more checks and longer run time.

Interview Connect

Understanding how scripts scale with input size helps you write efficient monitoring tools and explain your code clearly in real work or interviews.

Self-Check

"What if we stored the output of df -h once before the loop instead of calling it inside the loop? How would the time complexity change?"