0
0
Bash Scriptingscripting~5 mins

trap for cleanup on exit in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: trap for cleanup on exit
O(n)
Understanding Time Complexity

When using trap in bash to clean up on exit, it is important to understand how the script's running time changes as input grows.

We want to see how the cleanup action affects the total work done by the script.

Scenario Under Consideration

Analyze the time complexity of the following bash script using trap for cleanup.

#!/bin/bash

trap 'echo "Cleaning up..."; rm -f temp_file.txt' EXIT

for i in $(seq 1 $1); do
  echo "Line $i" >> temp_file.txt
  sleep 0.01
 done

This script writes lines to a temporary file in a loop and uses trap to delete the file when the script exits.

Identify Repeating Operations

Look at what repeats as input size changes.

  • Primary operation: The for loop writing lines to the file.
  • How many times: Exactly n times, where n is the input argument.
  • Cleanup operation: The trap runs once on exit, deleting the file.
How Execution Grows With Input

As the input number n grows, the loop runs more times, but the cleanup runs only once.

Input Size (n)Approx. Operations
1010 writes + 1 cleanup
100100 writes + 1 cleanup
10001000 writes + 1 cleanup

Pattern observation: The main work grows with n, but cleanup cost stays the same.

Final Time Complexity

Time Complexity: O(n)

This means the script's running time grows linearly with the number of lines written, while cleanup cost is constant.

Common Mistake

[X] Wrong: "The cleanup inside trap runs every loop iteration, so it adds to the loop's time."

[OK] Correct: The trap command runs only once when the script exits, not during the loop, so it does not multiply with input size.

Interview Connect

Understanding how cleanup commands run helps you write scripts that manage resources well without slowing down your main work.

Self-Check

What if the cleanup command inside trap also looped over n items? How would the time complexity change?