T.I.L. CLI flag handling in Bash using getopts
I'm not sure how I've never come across this before but while looking through the Scaleway Kosmos multi-cloud init script I dicovered the getopts
utility.
getopts
makes it easier to parse arguments passed to a shell script by defining which letters your script supports. It supports both boolean and string style arguments but only supports single letter flags. (e.g. -h
and not --help
)
Example usage:
#!/bin/bash
NAME="World"
FORCE=false
showHelp() {
echo "Usage: example.sh [args]"
exit 0
}
while getopts 'hfn:' FLAG
do
case $FLAG in
h) showHelp ;;
f) FORCE=true ;;
n) NAME=$OPTARG ;;
*) echo "Unsupported argument flag passed" ;;
esac
done
echo "Hello, $NAME"
Notice the :
following the n
? That indicates that a value should follow the argument flag (n
in this example) and will be made available as the OPTARG
variable.