Parallel execution patterns in Bash Scripting - Time & Space Complexity
When running tasks in parallel in bash scripts, it is important to understand how the total time changes as we add more tasks.
We want to know how the execution time grows when multiple commands run at the same time.
Analyze the time complexity of the following bash script using parallel execution.
for file in *.txt; do
cat "$file" &
done
wait
This script runs the cat command on each text file in the folder at the same time, then waits for all to finish.
Look for repeated actions that take time.
- Primary operation: Running
caton each file. - How many times: Once per file, all started in parallel.
Since all commands run at the same time, total time depends mostly on the longest single command.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Time of longest cat among 10 files |
| 100 | Time of longest cat among 100 files |
| 1000 | Time of longest cat among 1000 files |
Pattern observation: Total time grows with the longest single task, not the number of tasks.
Time Complexity: O(1)
This means the total time stays about the same no matter how many tasks run, assuming enough resources to run all in parallel.
[X] Wrong: "Running more tasks in parallel always takes more time overall."
[OK] Correct: When tasks run truly in parallel, total time depends on the longest task, not the count of tasks.
Understanding how parallel execution affects time helps you write faster scripts and shows you can think about efficiency in real situations.
What if we limit the number of parallel tasks to 5 at a time? How would the time complexity change?