0
0
Bash Scriptingscripting~5 mins

Temporary files (mktemp) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Temporary files (mktemp)
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: The for loop runs mktemp command n times.
  • How many times: Exactly once per loop iteration, so n times total.
How Execution Grows With Input

Each time we increase n, the number of temporary files created grows linearly.

Input Size (n)Approx. Operations
1010 calls to mktemp
100100 calls to mktemp
10001000 calls to mktemp

Pattern observation: The total work grows directly in proportion to n. Double n, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create temporary files grows linearly with the number of files you want to create.

Common Mistake

[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.

Interview Connect

Understanding how loops and external commands like mktemp scale helps you write efficient scripts and explain your reasoning clearly in interviews.

Self-Check

What if we created temporary files inside a nested loop? How would the time complexity change?