0
0
Bash Scriptingscripting~5 mins

Accessing variables ($var and ${var}) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Accessing variables ($var and ${var})
O(n)
Understanding Time Complexity

When we use variables in bash scripts, we often access their values using $var or ${var} syntax.

We want to understand how the time it takes to access these variables changes as the script grows or uses more variables.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#!/bin/bash

var="Hello"
echo $var

var2="World"
echo ${var2}

for i in 1 2 3 4 5; do
  echo $var
  echo ${var2}
done

This script sets two variables and prints them once, then prints them inside a loop five times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing variables using $var and ${var2} inside the loop.
  • How many times: The variable access happens 2 times per loop iteration, repeated 5 times.
How Execution Grows With Input

Each loop iteration accesses variables twice. As the number of iterations grows, the total variable accesses grow proportionally.

Input Size (n)Approx. Operations
1020 variable accesses
100200 variable accesses
10002000 variable accesses

Pattern observation: The number of variable accesses grows linearly with the number of loop iterations.

Final Time Complexity

Time Complexity: O(n)

This means the time to access variables grows directly in proportion to how many times you access them in a loop.

Common Mistake

[X] Wrong: "Accessing a variable like $var is instant and does not add to execution time as the script grows."

[OK] Correct: While each access is fast, if you access variables many times in loops, the total time adds up and grows with the number of accesses.

Interview Connect

Understanding how variable access scales helps you write efficient scripts and shows you can think about performance even in simple tasks.

Self-Check

What if we replaced the loop with nested loops accessing variables multiple times? How would the time complexity change?