Local variables (local keyword) in Bash Scripting - Time & Space Complexity
When using local variables in bash functions, it is helpful to understand how this affects the script's running time.
We want to see how the use of local changes the cost as the script runs.
Analyze the time complexity of this bash function using local variables.
function count_lines() {
local file="$1"
local count=0
while IFS= read -r line; do
((count++))
done < "$file"
echo "$count"
}
count_lines "myfile.txt"
This function counts the number of lines in a file using local variables inside the function.
Look at what repeats as the script runs.
- Primary operation: Reading each line of the file one by one.
- How many times: Once for every line in the file (n times).
As the file gets bigger, the function reads more lines, so it takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 line reads and increments |
| 100 | About 100 line reads and increments |
| 1000 | About 1000 line reads and increments |
Pattern observation: The time grows roughly in direct proportion to the number of lines.
Time Complexity: O(n)
This means the time to run grows linearly with the number of lines in the file.
[X] Wrong: "Using local variables makes the function run slower because it adds extra work."
[OK] Correct: Declaring variables as local only affects variable scope, not how many times the loop runs. The main cost is reading lines, which stays the same.
Understanding how local variables affect script performance helps you write clear and efficient bash functions, a useful skill in many scripting tasks.
What if we removed the local keyword and used global variables instead? How would the time complexity change?