Command-line arguments ($1, $2, ...) in Bash Scripting - Time & Space Complexity
When using command-line arguments in a bash script, it's important to know how the script's work changes as you add more arguments.
We want to see how the script's running time grows when it reads and uses these arguments.
Analyze the time complexity of the following code snippet.
#!/bin/bash
for arg in "$@"; do
echo "Argument: $arg"
done
# This script prints each command-line argument one by one.
This script loops through all given command-line arguments and prints each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each command-line argument.
- How many times: Once for each argument provided.
Each new argument adds one more loop step, so the work grows steadily with the number of arguments.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 echo commands |
| 100 | 100 echo commands |
| 1000 | 1000 echo commands |
Pattern observation: The work increases directly in proportion to the number of arguments.
Time Complexity: O(n)
This means the script takes longer in a straight line as you add more arguments.
[X] Wrong: "The script runs in the same time no matter how many arguments there are."
[OK] Correct: Each argument adds a step to the loop, so more arguments mean more work and more time.
Understanding how loops over inputs affect time helps you explain script efficiency clearly and confidently in real-world tasks.
"What if the script only printed the first argument instead of all? How would the time complexity change?"