Progress indicators in Bash Scripting - Time & Space Complexity
When we add progress indicators in bash scripts, we want to know how much extra work they add as the task grows.
We ask: How does showing progress affect the script's running time as input size increases?
Analyze the time complexity of the following code snippet.
#!/bin/bash
count=0
for file in /path/to/files/*; do
# Process each file
echo "Processing $file"
((count++))
# Show progress every 10 files
if (( count % 10 == 0 )); then
echo "Processed $count files so far..."
fi
done
This script processes files one by one and prints a progress message every 10 files.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each file in the directory.
- How many times: Once per file, so as many times as there are files (n).
- Progress check: Every 10 files, a message is printed (about n/10 times).
As the number of files grows, the script processes each file once and prints progress messages occasionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 file processes + 1 progress message |
| 100 | 100 file processes + 10 progress messages |
| 1000 | 1000 file processes + 100 progress messages |
Pattern observation: The main work grows linearly with n, and progress messages grow much slower, about n divided by 10.
Time Complexity: O(n)
This means the script's running time grows directly in proportion to the number of files processed.
[X] Wrong: "Printing progress every file makes the script much slower, changing the time complexity."
[OK] Correct: Printing progress messages adds some work, but it happens at fixed intervals, so it doesn't change the overall linear growth with input size.
Understanding how progress indicators affect script speed shows you can balance user feedback with efficiency, a useful skill in real scripting tasks.
"What if we printed a progress message after processing every single file instead of every 10 files? How would the time complexity change?"