Temporary files (mktemp) in Bash Scripting - Time & Space Complexity
When creating temporary files in a script, it is important to understand how the time to create these files grows as you create more of them.
We want to know how the script's running time changes when making many temporary files using mktemp.
Analyze the time complexity of the following code snippet.
for i in $(seq 1 $n); do
tmpfile=$(mktemp)
echo "Temporary file created: $tmpfile"
done
This script creates n temporary files one after another and prints their names.
- Primary operation: The
forloop runsmktempcommandntimes. - How many times: Exactly once per loop iteration, so
ntimes total.
Each time we increase n, the number of temporary files created grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to mktemp |
| 100 | 100 calls to mktemp |
| 1000 | 1000 calls to mktemp |
Pattern observation: The total work grows directly in proportion to n. Double n, double the work.
Time Complexity: O(n)
This means the time to create temporary files grows linearly with the number of files you want to create.
[X] Wrong: "Creating temporary files with mktemp is instant and does not depend on how many files I create."
[OK] Correct: Each call to mktemp takes some time, so creating many files adds up and takes longer as n grows.
Understanding how loops and external commands like mktemp scale helps you write efficient scripts and explain your reasoning clearly in interviews.
What if we created temporary files inside a nested loop? How would the time complexity change?