Function arguments ($1, $2 inside function) in Bash Scripting - Time & Space Complexity
We want to see how the time to run a bash function changes when it uses arguments like $1 and $2.
How does the number of arguments affect the work inside the function?
Analyze the time complexity of the following code snippet.
my_function() {
echo "First argument: $1"
echo "Second argument: $2"
}
my_function arg1 arg2
This function prints the first two arguments it receives. It uses $1 and $2 inside the function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing and printing two arguments once each.
- How many times: Exactly two times, once per argument.
Each argument is accessed and printed once. If we increase the number of arguments, but the function only uses $1 and $2, the work stays the same.
| Input Size (number of arguments) | Approx. Operations |
|---|---|
| 2 | 2 (access and print $1 and $2) |
| 10 | 2 (still only $1 and $2 used) |
| 100 | 2 (no change, only first two arguments matter) |
Pattern observation: The work does not grow with more arguments if the function only uses $1 and $2.
Time Complexity: O(1)
This means the function runs in constant time no matter how many arguments are passed, because it only uses the first two.
[X] Wrong: "More arguments always mean more work inside the function."
[OK] Correct: If the function only uses $1 and $2, extra arguments are ignored, so the work stays the same.
Understanding how function arguments affect work helps you explain efficiency clearly and shows you know how bash functions handle inputs.
"What if the function used a loop to print all arguments using $@? How would the time complexity change?"