How to Use getopts in Bash for Command-Line Options
Use
getopts in bash to parse command-line options by specifying option letters and handling them in a loop. It processes options one by one, allowing you to easily manage flags and arguments in your script.Syntax
The basic syntax of getopts is:
getopts optstring variable
Here, optstring defines the valid option letters. If an option requires an argument, follow it with a colon :. The variable stores the current option letter.
Inside a while loop, getopts processes each option. Use $OPTARG to access the argument of an option that requires one.
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" ;; esac done
Example
This example script uses getopts to parse options -a, -b with an argument, and -c. It prints messages based on the options provided.
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" exit 1 ;; esac done # Example usage: # ./script.sh -a -b value -c
Output
Option a triggered
Option b triggered with argument: value
Option c triggered
Common Pitfalls
Common mistakes when using getopts include:
- Not including a colon
:after options that require arguments in theoptstring. - Using
$1instead of$OPTARGto get option arguments. - Not handling invalid options or missing arguments properly.
- Forgetting to shift positional parameters after parsing options.
Always check for invalid options and missing arguments to make your script robust.
bash
# Wrong: Missing colon for option b while getopts "ab" opt; do case $opt in b) echo "Option b argument: $1" # Incorrect, should use $OPTARG ;; esac done # Right: while getopts "ab:" opt; do case $opt in b) echo "Option b argument: $OPTARG" ;; esac done
Quick Reference
| Symbol | Meaning |
|---|---|
| a | Option 'a' without argument |
| b: | Option 'b' requires an argument |
| c | Option 'c' without argument |
| $OPTARG | Variable holding the argument for options that require one |
| $opt | Variable holding the current option letter |
| getopts | Built-in command to parse options in a loop |
Key Takeaways
Use getopts with a while loop to parse command-line options one by one.
Add a colon after option letters in optstring to indicate they require arguments.
Access option arguments with $OPTARG, not $1 or other variables.
Always handle invalid options and missing arguments to avoid script errors.
Shift positional parameters if you want to process non-option arguments after getopts.