touch (create empty files) in Linux CLI - Time & Space Complexity
We want to understand how the time to create files using the touch command changes as we create more files.
How does the work grow when we ask the system to make many empty files?
Analyze the time complexity of the following code snippet.
for i in $(seq 1 1000); do
touch file_$i.txt
done
This script creates 1000 empty files named file_1.txt to file_1000.txt one by one.
- Primary operation: The
touchcommand inside the loop creates one file each time. - How many times: It runs once for each file, so 1000 times in this example.
Each new file requires one touch command. So if you double the number of files, you double the work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 touch commands |
| 100 | 100 touch commands |
| 1000 | 1000 touch commands |
Pattern observation: The number of operations grows directly with the number of files.
Time Complexity: O(n)
This means the time to create files grows in a straight line with how many files you want to make.
[X] Wrong: "Creating many files with touch happens instantly no matter how many files."
[OK] Correct: Each file creation takes some time, so more files mean more total time.
Understanding how commands scale with input size helps you write scripts that run efficiently and predict how long tasks will take.
"What if we used a single command to create all files at once? How would the time complexity change?"