Function definition in Bash Scripting - Time & Space Complexity
When we write functions in bash scripts, it is helpful to know how their running time changes as we give them more work.
We want to see how the time to run a function grows when the input size changes.
Analyze the time complexity of the following code snippet.
function greet() {
local name="$1"
echo "Hello, $name!"
}
greet "Alice"
This code defines a simple function that prints a greeting for one name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single echo command inside the function.
- How many times: The function runs once per call, no loops or recursion inside.
Since the function only prints one message, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 1 (one echo) |
| 10 | 1 (still one echo per call) |
| 100 | 1 (no loops, so same time) |
Pattern observation: The time stays the same no matter the input size.
Time Complexity: O(1)
This means the function runs in constant time, taking the same time regardless of input size.
[X] Wrong: "The function takes longer if the input string is longer."
[OK] Correct: The function just prints the input once, so time does not grow with input length in a meaningful way here.
Understanding how simple functions behave helps build a strong foundation for analyzing more complex scripts later.
"What if the function included a loop that printed the name multiple times? How would the time complexity change?"