File existence checks in Bash Scripting - Time & Space Complexity
When checking if files exist in a script, it is important to understand how the time taken grows as the number of files increases.
We want to know how the script's running time changes when we check more files.
Analyze the time complexity of the following code snippet.
for file in "$@"; do
if [ -e "$file" ]; then
echo "$file exists"
else
echo "$file does not exist"
fi
done
This script loops through each file name given as input and checks if it exists, printing a message for each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that checks each file's existence one by one.
- How many times: Once for each file passed as input.
As the number of files increases, the script checks each file once, so the total work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 file existence checks |
| 100 | 100 file existence checks |
| 1000 | 1000 file existence checks |
Pattern observation: The number of checks grows directly with the number of files.
Time Complexity: O(n)
This means the time to run the script grows in a straight line as you add more files to check.
[X] Wrong: "Checking one file or many files takes the same time because each check is fast."
[OK] Correct: Even if one check is quick, doing many checks adds up, so more files mean more total time.
Understanding how loops over files affect time helps you write scripts that scale well and shows you can think about efficiency clearly.
"What if we checked files in nested directories recursively? How would the time complexity change?"