Long option parsing in Bash Scripting - Time & Space Complexity
When a bash script reads long options from the command line, it checks each argument one by one.
We want to know how the time to process options grows as the number of arguments increases.
Analyze the time complexity of the following code snippet.
while [[ $# -gt 0 ]]; do
case "$1" in
--help)
echo "Show help" ;;
--version)
echo "Show version" ;;
--output=*)
output_file="${1#*=}" ;;
*)
echo "Unknown option: $1" ;;
esac
shift
done
This script loops through all command-line arguments and matches each against known long options.
- Primary operation: The while loop processes each argument once.
- How many times: It runs once per argument, so as many times as there are arguments.
Each argument adds one more loop cycle, so the work grows steadily with more arguments.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The time grows directly in proportion to the number of arguments.
Time Complexity: O(n)
This means the script takes longer in a straight line as you add more options to process.
[X] Wrong: "The script checks all options instantly no matter how many arguments there are."
[OK] Correct: The script must look at each argument one by one, so more arguments mean more work.
Understanding how loops grow with input size helps you explain script efficiency clearly and confidently.
"What if the script used nested loops to check each argument against a list of many valid options? How would the time complexity change?"