bash option parsing
Since I know I’m going to forget how to do it properly, this is a tiny
recipe to easily parse options in bash. I use getopts
(and not
getopt . !!! mind the S) that is a builtin shell command. help
getopts
to read the doco.
The snippet is pretty easy and self explanatory :
#!/bin/bash
usage()
{
DESCRIPTION=
cat << EOF
usage: $0 options
$DESCRIPTION
OPTIONS:
-h Show this message
-v Verbose
-d Debug
-f file
EOF
}
VERBOSE=
DEBUG=
FILE=
OTHERARGS=
while getopts "vhdf:" flag
do
case "$flag" in
f) FILE=$OPTARG ;;
d) set -x ; DEBUG=true;;
v) VERBOSE=true ;;
h) usage ; exit 0 ;;
esac
# echo "$flag" $OPTIND $OPTARG
done
if [ -z $FILE ]; then
shift $((OPTIND-1))
OTHERARGS="$@"
fi
if [ -n "$VERBOSE"] ; then
echo "verbose $VERBOSE"
echo "debug $DEBUG"
echo "file $FILE"
echo "other args $OTHERARGS"
fi
exit 0