Option parsing with getopts in Bash Scripting - Time & Space Complexity
When we use getopts in bash to handle options, it processes each option one by one.
We want to understand how the time it takes changes as the number of options grows.
Analyze the time complexity of the following code snippet.
while getopts ":ab:c" opt; do
case $opt in
a) echo "Option a" ;;
b) echo "Option b with value $OPTARG" ;;
c) echo "Option c" ;;
*) echo "Invalid option" ;;
esac
done
This code reads command-line options one at a time and handles them accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs once for each option found.
- How many times: It runs as many times as there are options in the input.
Each option adds one more loop cycle, so the work grows steadily with the number of options.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop cycles |
| 100 | About 100 loop cycles |
| 1000 | About 1000 loop cycles |
Pattern observation: The time grows directly in proportion to the number of options.
Time Complexity: O(n)
This means the time to parse options grows linearly as you add more options.
[X] Wrong: "getopts checks all options at once, so time stays the same no matter how many options there are."
[OK] Correct: getopts processes options one by one in a loop, so more options mean more work and more time.
Understanding how loops handle input size helps you explain script efficiency clearly and confidently.
"What if we added nested loops inside the getopts loop to process each option's value? How would the time complexity change?"