set -u for undefined variable errors in Bash Scripting - Time & Space Complexity
When using set -u in bash, the script stops if it tries to use a variable that has not been set.
We want to see how this affects the script's running time as the input changes.
Analyze the time complexity of the following bash script snippet.
#!/bin/bash
set -u
for file in "$@"; do
echo "Processing $file"
# Use variable that might be undefined
echo "Value: ${VALUE}"
done
This script loops over all input arguments and tries to print a variable VALUE that may not be set, causing an error if set -u is active.
Look for loops or repeated commands that affect time.
- Primary operation: The
forloop over input arguments, but exits early on undefined variable. - How many times: Only once (first iteration), regardless of number of arguments.
The script performs only one loop iteration (processes first file) before exiting due to set -u error, so work stays constant.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 loop iteration |
| 100 | 1 loop iteration |
| 1000 | 1 loop iteration |
Pattern observation: The number of operations is constant, independent of the number of inputs.
Time Complexity: O(1)
This means the script's running time stays constant as you add more input files; it stops after the first due to the error.
[X] Wrong: "Using set -u will make the script run slower because it checks variables every time."
[OK] Correct: The main time cost comes from looping over inputs, not from checking variables. The set -u check is very fast and does not add noticeable delay per iteration.
Understanding how loops and error checks affect script speed helps you write reliable and efficient automation scripts.
What if we moved the echo "Value: $VALUE" line outside the loop? How would the time complexity change?