Read-only variables (readonly) in Bash Scripting - Time & Space Complexity
We want to understand how the time it takes to run a script changes when using read-only variables in bash.
Specifically, does making a variable read-only affect how long the script takes as it runs?
Analyze the time complexity of the following bash script using readonly variables.
#!/bin/bash
readonly MAX=1000
for ((i=1; i<=MAX; i++)); do
echo "Number: $i"
done
This script sets a read-only variable MAX and loops from 1 to MAX, printing each number.
Look at what repeats in the script.
- Primary operation: The for-loop runs and prints a line each time.
- How many times: It runs MAX times, which is 1000 here.
As MAX grows, the loop runs more times.
| Input Size (MAX) | Approx. Operations |
|---|---|
| 10 | 10 loops and prints |
| 100 | 100 loops and prints |
| 1000 | 1000 loops and prints |
Pattern observation: The number of operations grows directly with MAX. Double MAX, double the work.
Time Complexity: O(n)
This means the time grows in a straight line with the size of MAX. More MAX means more loops.
[X] Wrong: "Making a variable readonly makes the loop run faster or slower."
[OK] Correct: The readonly keyword just prevents changes to the variable. It does not affect how many times the loop runs or how long each loop takes.
Understanding how readonly variables behave helps you write safer scripts without worrying about performance changes. This shows you can focus on correctness and still predict your script's speed.
"What if we replaced the readonly variable with a normal variable that changes inside the loop? How would the time complexity change?"