Introduction
Option parsing with getopts helps your script understand and handle user inputs like flags and options easily.
getopts optstring variable # optstring: string of option letters. A letter followed by : means that option needs an argument. # variable: name of the variable to store the current option letter.
while getopts "hf:" opt; do case $opt in h) echo "Help option selected" ;; f) echo "File option with argument: $OPTARG" ;; *) echo "Invalid option" ;; esac done
while getopts "a:b" opt; do case $opt in a) echo "Option a with argument: $OPTARG" ;; b) echo "Option b selected" ;; esac done
#!/bin/bash while getopts "hu:f:" opt; do case $opt in h) echo "Usage: $0 [-h] [-u username] [-f filename]" exit 0 ;; u) echo "Username set to: $OPTARG" ;; f) echo "Filename set to: $OPTARG" ;; *) echo "Invalid option: -$opt" >&2 exit 1 ;; esac done
getopts command in bash scripting?getopts is a built-in bash command designed to handle command-line options and their arguments in scripts.getopts.getopts in a bash script?getopts is inside a while loop with a case statement to handle each option.while getopts "ab:" opt; do ... case $opt in a)... b)... esac; done. Other options use invalid control structures like for or if, or incorrect command syntax../script.sh -a -b value?while getopts "ab:" opt; do
case $opt in
a) echo "Option a set" ;;
b) echo "Option b set with $OPTARG" ;;
esac
done-a and -b value. Option a has no argument, b requires an argument.-a, sets $opt to a, and echoes Option a set
Option a set
Option b set with -b set with value set. Next, -b value sets $opt to b and $OPTARG to value, echoing Option a set
Option b set with -b set with value.while getopts "ab:" opt; do
case $opt in
a) echo "Option a" ;;
b) echo "Option b with $OPTARG" ;;
?) echo "Invalid option" ;;
esac
done-b but no argument?-f (file name) and -v (verbose flag). Which getopts string and case structure correctly handle these options, where -f requires an argument and -v does not?-f requires an argument, so it must be followed by a colon: f:. Option -v is a flag, no colon needed. The correct string has ':' immediately after 'f', such as "vf:". Strings like "fv:" place ':' after 'v', making -v require an argument, which is wrong; missing ':' means no arguments expected.v by setting verbose flag and f by assigning $OPTARG to file variable. getopts string: "vf:"; case: v) verbose=1 ;; f) file=$OPTARG ;; matches this correctly.Pass the test and this pattern moves unknown