0
0
Bash Scriptingscripting~5 mins

Read-only variables (readonly) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Read-only variables (readonly)
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As MAX grows, the loop runs more times.

Input Size (MAX)Approx. Operations
1010 loops and prints
100100 loops and prints
10001000 loops and prints

Pattern observation: The number of operations grows directly with MAX. Double MAX, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the size of MAX. More MAX means more loops.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we replaced the readonly variable with a normal variable that changes inside the loop? How would the time complexity change?"