getopts
(Option Parsing)Creating modular, maintainable Bash scripts is crucial for large projects. This includes separating code into reusable files and parsing CLI flags using getopts
.
lib/log.sh
)Modular scripts allow you to split reusable functions into external .sh
files.
lib/log.sh
#!/bin/bash
log_info() {
echo "[INFO] $1"
}
log_error() {
echo "[ERROR] $1" >&2
}
#!/bin/bash
source lib/log.sh
log_info "Script started"
log_error "Something went wrong"
source
to Import Filessource ./utils.sh
or simply:
. ./utils.sh
This runs the file in the current shell, allowing access to its functions and variables.
getopts
getopts
is a Bash built-in used to handle command-line flags like -f
, -v
, -h
.
while getopts ":f:v:h" opt; do
case $opt in
f) file=$OPTARG ;;
v) value=$OPTARG ;;
h) echo "Help message"; exit 0 ;;
\?) echo "Invalid option: -$OPTARG" >&2 ;;
esac
done
#!/bin/bash
while getopts ":n:a:" opt; do
case $opt in
n) name="$OPTARG" ;;
a) age="$OPTARG" ;;
\?) echo "Invalid option: -$OPTARG" ;;
esac
done
echo "Name: $name"
echo "Age: $age"
Run it like:
./script.sh -n Kashif -a 24
getopts
Symbol | Meaning |
---|---|
: after a letter |
Option requires an argument |
\? |
Catch invalid options |
: (before string) |
Suppress error messages (silent mode) |
getopt
)Bash getopts
does not support long options like --help
directly. You can use GNU getopt
for advanced parsing:
getopt -o h --long help -- "$@"
Practice | Benefit |
---|---|
Use source for reusable code |
Cleaner scripts |
Group related functions | Easier maintenance |
Always validate arguments | Prevent errors |
Provide a -h or --help flag |
Friendly UX |
📁 File:
advance/libraries-getopts.md
Author: Kashif Alam