Style guide and conventions in Bash Scripting - Time & Space Complexity
When writing bash scripts, understanding time complexity helps ensure they scale well with larger inputs.
We want to see how the script's running time grows as the input size increases.
Analyze the time complexity of the following bash script snippet.
#!/bin/bash
for file in /var/log/*; do
if [[ $file == *.log ]]; then
echo "Processing $file"
fi
done
This script lists files in /var/log and prints a message for each file ending with .log.
Look for loops or repeated actions in the script.
- Primary operation: The
forloop goes through each file in the directory. - How many times: Once for every file found in /var/log.
As the number of files grows, the script runs more checks and prints more messages.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop checks and prints |
| 100 | About 100 loop checks and prints |
| 1000 | About 1000 loop checks and prints |
Pattern observation: The work grows directly with the number of files.
Time Complexity: O(n)
This means the script takes longer in a straight line as the number of files increases.
[X] Wrong: "Using ls inside the loop makes it slower each time."
[OK] Correct: The ls runs once before the loop starts, so it does not repeat inside the loop.
Understanding how loops grow with input helps you write scripts that stay fast and clear as they handle more data.
"What if we replaced ls /var/log with a command that lists files recursively? How would the time complexity change?"