tee for splitting output in Linux CLI - Time & Space Complexity
When using the tee command to split output in Linux, it's important to understand how the time to complete the command changes as the amount of output grows.
We want to know how the command's execution time scales with the size of the data being processed.
Analyze the time complexity of this command that splits output to a file and the screen:
ls -l | tee output.txt
This command lists files in long format and uses tee to send the output both to the file output.txt and to the terminal.
Look at what repeats as the command runs:
- Primary operation: Reading each line of output from
ls -land writing it twice (once to the file, once to the screen). - How many times: Once for every line of output produced by
ls -l.
As the number of files listed grows, the output lines grow too. Each line is processed and written twice.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 writes (10 lines x 2 writes each) |
| 100 | About 200 writes |
| 1000 | About 2000 writes |
Pattern observation: The total work grows roughly twice as fast as the number of output lines.
Time Complexity: O(n)
This means the time to complete grows directly in proportion to the number of output lines.
[X] Wrong: "Using tee doubles the time complexity to O(2n), which is slower in a big way."
[OK] Correct: The constant factor 2 is ignored in Big-O notation because it doesn't change how the time grows as input gets very large. The growth is still linear.
Understanding how commands like tee affect performance helps you reason about data flow in scripts and pipelines, a useful skill in many automation tasks.
What if we used tee to write output to multiple files instead of one? How would the time complexity change?