Linux Shell Scripting Cheat Sheet/Parse short options with getopts

Handle flags in shell scripts.

Section: Script Execution and Utilities

Parse short options with getopts

bash
bash
while getopts ':f:n:' opt; do case "$opt" in f) file="$OPTARG" ;; n) count="$OPTARG" ;; esac; done
Explanation

Useful for small production scripts with predictable CLI flags.

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 Execution and Utilities
Use bash shebang
Start a Bash script with an explicit interpreter.
OpenIn sheetbashsame section
Make script executable
Add execute bit to a script.
OpenIn sheetbashsame section
Run shell script
Execute a script from the current directory.
OpenIn sheetbashsame section
Trace script execution
Print commands as they execute.
OpenIn sheetbashsame section
Lint shell script
Static-analyze shell scripts for bugs.
OpenIn sheetbashsame section
Assign shell variable
Set a shell variable in the current shell.
OpenIn sheetbash1 tag match