Command chaining (&&, ||, ;) in Linux CLI - Time & Space Complexity
We want to understand how the time to run chained commands changes as we add more commands.
How does the total work grow when commands are linked with &&, ||, or ; ?
Analyze the time complexity of the following command chaining example.
cmd1 && cmd2 || cmd3; cmd4
This runs cmd1, then cmd2 if cmd1 succeeds, else cmd3, and finally cmd4 regardless.
Here, each command runs once in sequence depending on previous results.
- Primary operation: Executing each command once.
- How many times: Number of commands in the chain (4 here).
As you add more commands chained, the total work grows roughly by the number of commands.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 commands | 2 executions |
| 5 commands | 5 executions |
| 10 commands | 10 executions |
Pattern observation: The total steps grow linearly with the number of commands.
Time Complexity: O(n)
This means the total time grows directly with how many commands you chain.
[X] Wrong: "All commands always run no matter what, so time is always n times the longest command."
[OK] Correct: With && and ||, some commands may skip running depending on success or failure, so actual time can be less.
Knowing how command chaining affects execution helps you write efficient scripts and understand shell behavior clearly.
What if we replaced all && and || with ; ? How would the time complexity change?