Script Arguments with getopts
getopts is like a receptionist who reads the little switches you add to a command, such as a flag and its value, and hands them neatly to your script.
In this page:
Syntax
while getopts "optstring" option; do
case $option in
a) commands ;;
b) value=$OPTARG ;;
*) usage ;;
esac
done
Script Arguments with getopts
getopts parses short command-line flags like -f file or -v, handling common conventions like combined flags and required option arguments.
It's the standard, POSIX-compatible way to build a script with proper flag parsing instead of manually checking $1, $2. Each recognized option is handled in a case inside the while getopts loop.
Note:
A colon after an option letter in the options string, like
"f:", means that option requires an argument.Example: Script Arguments with getopts
#!/bin/bash
verbose=false
filename=""
while getopts "vf:" opt; do
case $opt in
v) verbose=true ;;
f) filename=$OPTARG ;;
*) echo "Unknown option" ;;
esac
done
echo "Verbose: $verbose"
echo "Filename: $filename"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting the colon after an option letter that needs a value.
- Forgetting to use
shift $((OPTIND-1))after parsing options. - Expecting
getoptsto handle long options like--help.
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments