Parsing Options with the getopts Command
The getopts
command is a built-in Bash function that provides a convenient way to parse command-line options. It allows you to easily handle both single-character and multi-character options in your Bash scripts.
Syntax and Usage
The basic syntax for using getopts
is as follows:
while getopts "abc:d" opt; do
case $opt in
a) ## Handle the 'a' option ;;
b) ## Handle the 'b' option ;;
c) ## Handle the 'c' option with an argument ;;
d) ## Handle the 'd' option ;;
\?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
esac
done
In this example, the getopts
command is used to parse options that are specified with a single character, such as -a
, -b
, -c <arg>
, and -d
.
The getopts
command stores the current option in the $opt
variable, which can then be used in a case
statement to handle the different options.
Handling Single-character Options
Single-character options are the most common type of command-line options. They are typically preceded by a single hyphen (-
), such as -v
, -h
, or -o
.
Here's an example of how to handle single-character options using getopts
:
#!/bin/bash
while getopts "vho:" opt; do
case $opt in
v) echo "Verbose mode enabled" ;;
h) echo "Usage: $0 [-v] [-h] [-o output_file]" ;;
o) output_file="$OPTARG" ;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
In this example, the script accepts three options: -v
(verbose mode), -h
(display help), and -o
(output file).
Handling Multi-character Options
While single-character options are common, Bash also supports multi-character options, which are preceded by two hyphens (--
), such as --verbose
or --output-file
.
To handle multi-character options with getopts
, you can use the colon (:
) character in the option string. Here's an example:
#!/bin/bash
while getopts "v-:h-:o-:" opt; do
case $opt in
v) echo "Verbose mode enabled" ;;
h) echo "Usage: $0 [--verbose] [--help] [--output-file=<file>]" ;;
o) echo "Output file: $OPTARG" ;;
-) case $OPTARG in
verbose) echo "Verbose mode enabled" ;;
help) echo "Usage: $0 [--verbose] [--help] [--output-file=<file>]" ;;
output-file) output_file="$OPTVALUE" ;;
*)
echo "Invalid option: --$OPTARG" >&2
exit 1
;;
esac ;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
In this example, the script accepts three multi-character options: --verbose
, --help
, and --output-file=<file>
.
By using the getopts
command, you can easily parse and handle both single-character and multi-character options in your Bash scripts, making them more flexible and user-friendly.