Bash Scripting Patterns and Practical Recipes/Parse short options with getopts

Parse short options using the getopts builtin.

Section: Script Structure

Parse short options with getopts

bash
bash
while getopts ':f:o:v' opt; do
  case $opt in
    f) file=$OPTARG ;;
    o) output=$OPTARG ;;
    v) verbose=1 ;;
    \?) echo "invalid option: -$OPTARG" ;;
  esac
done
Explanation

Good for POSIX-style short flags in shell scripts.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Script Structure
Shift parsed options away
Drop parsed options after getopts completes.
OpenIn sheetbashsame section
Parse flags with while/case
Implement manual flag parsing in Bash.
OpenIn sheetbashsame section
Portable Bash shebang
Use env to locate Bash on PATH.
OpenIn sheetbashsame section
Get script directory
Resolve the directory of the current script.
OpenIn sheetbashsame section
Create temp file
Create a secure temporary file.
Simple log function
Print timestamped log lines.