-
-
Notifications
You must be signed in to change notification settings - Fork 1
Linux getopts Guide
Mattscreative edited this page Dec 5, 2025
·
2 revisions
Complete beginner-friendly guide to getopts on Linux, covering Arch Linux, CachyOS, and other distributions including built-in option parsing, shell option handling, and script argument parsing.
Basic usage:
#!/bin/bash
while getopts "hv" opt; do
case $opt in
h)
echo "Help"
;;
v)
VERBOSE=1
;;
esac
doneOption format:
# Option string: "hv"
# h = help flag
# v = verbose flagBasic flags:
#!/bin/bash
while getopts "hv" opt; do
case $opt in
h) echo "Help message" ;;
v) VERBOSE=1 ;;
\?) echo "Invalid option" ;;
esac
doneMultiple flags:
# Multiple options
while getopts "abc" opt; do
case $opt in
a) OPTION_A=1 ;;
b) OPTION_B=1 ;;
c) OPTION_C=1 ;;
esac
doneOption with value:
# Option with argument
while getopts "f:" opt; do
case $opt in
f)
FILE=$OPTARG
;;
esac
done
# Usage: script.sh -f filename.txtOptional value:
# Optional argument (GNU extension)
while getopts "f::" opt; do
case $opt in
f)
FILE=${OPTARG:-default.txt}
;;
esac
doneHandle errors:
#!/bin/bash
while getopts "hv" opt; do
case $opt in
h) echo "Help" ;;
v) VERBOSE=1 ;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires argument" >&2
exit 1
;;
esac
doneCheck installation:
# getopts is built-in shell command
# Always available in bash
# Check bash
which bashThis guide covered getopts usage, built-in option parsing, and script argument handling for Arch Linux, CachyOS, and other distributions.
- getopt Guide - External option parser
- Bash Scripting Guide - Scripting basics
-
getopts Documentation:
man bash(built-in)
This guide covers Arch Linux, CachyOS, and other Linux distributions. For distribution-specific details, refer to your distribution's documentation.