Script Arguments with getopts
In this page:
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
🔒
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