How to Parse Options in Bash Script: Simple Guide
To parse options in a bash script, use the
getopts built-in command which processes short options one by one. Define option letters and handle them in a while loop with a case statement to respond to each option.Syntax
The basic syntax for parsing options with getopts is:
getopts optstring variable: Reads options from the script's arguments.optstring: A string of option letters to recognize; a colon:after a letter means that option requires an argument.variable: The name of the variable that will hold the current option letter.- Use a
whileloop to process all options. - Use a
casestatement inside the loop to handle each option.
bash
while getopts "ab:c" opt; do case $opt in a) echo "Option a triggered" ;; b) echo "Option b triggered with argument: $OPTARG" ;; c) echo "Option c triggered" ;; *) echo "Invalid option: -$opt" ;; esac done
Example
This example script parses options -a, -b with an argument, and -c. It prints messages based on the options given.
bash
#!/bin/bash while getopts "ab:c" opt; do case $opt in a) echo "Option a triggered" ;; b) echo "Option b triggered with argument: $OPTARG" ;; c) echo "Option c triggered" ;; *) echo "Invalid option: -$opt" ;; esac done
Output
Option a triggered
Option b triggered with argument: value
Option c triggered
Common Pitfalls
Common mistakes when parsing options in bash scripts include:
- Not using a colon
:after option letters that require arguments inoptstring. - Forgetting to handle the case when an option requires an argument but none is provided.
- Not shifting the positional parameters after
getoptsprocessing, which can cause issues if you want to process non-option arguments later. - Using
$OPTARGincorrectly outside thegetoptsloop.
Example of wrong and right usage:
bash
# Wrong: Missing colon for option b which needs an argument while getopts "ab c" opt; do case $opt in b) echo "Option b argument: $OPTARG" ;; # OPTARG will be empty esac done # Right: Colon after b to expect argument while getopts "ab:c" opt; do case $opt in b) echo "Option b argument: $OPTARG" ;; # OPTARG holds the argument esac done
Quick Reference
| Symbol | Meaning |
|---|---|
| a | Option letter 'a' without argument |
| b: | Option letter 'b' requires an argument |
| OPTARG | Variable holding the argument value for options that require one |
| getopts | Built-in command to parse options |
| $opt | Variable holding the current option letter |
| while getopts ... | Loop to process all options |
| case $opt in ... | Handle each option inside the loop |
Key Takeaways
Use getopts with a while loop and case statement to parse options in bash scripts.
Add a colon after option letters in optstring to indicate they require arguments.
Access option arguments with the OPTARG variable inside the getopts loop.
Shift positional parameters if you need to handle non-option arguments after parsing.
Always handle invalid options to provide helpful error messages.