0
0
Bash Scriptingscripting~5 mins

Command-line arguments ($1, $2, ...) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Command-line arguments ($1, $2, ...)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each command-line argument.
  • How many times: Once for each argument provided.
How Execution Grows With Input

Each new argument adds one more loop step, so the work grows steadily with the number of arguments.

Input Size (n)Approx. Operations
1010 echo commands
100100 echo commands
10001000 echo commands

Pattern observation: The work increases directly in proportion to the number of arguments.

Final Time Complexity

Time Complexity: O(n)

This means the script takes longer in a straight line as you add more arguments.

Common Mistake

[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.

Interview Connect

Understanding how loops over inputs affect time helps you explain script efficiency clearly and confidently in real-world tasks.

Self-Check

"What if the script only printed the first argument instead of all? How would the time complexity change?"