I am looking for a reusable code snippet that does command line argument validation for bash.
Ideally something akin to the functionality offered by Apache Commons CLI:<
This is the solution I use (found it on the net somewhere, probably here itself, don't remember for sure). Please note that the GNU getopt (/usr/bin/getopt
) does support single dash long options (ant -projecthelp
style) using the option -a
, however I haven't used it so it is not shown in the example.
This code parses for 3 options: --host value
or -h value
, --port value
or -p value
and --table value
or -t value
. In case the required parameter isn't set, a test for it is
# Get and parse options using /usr/bin/getopt
OPTIONS=$(getopt -o h:p:t: --long host:,port:,table: -n "$0" -- "$@")
# Note the quotes around `$OPTIONS': they are essential for handling spaces in
# option values!
eval set -- "$OPTIONS"
while true ; do
case "$1" in
-h|--host) HOST=$2 ; shift 2 ;;
-t|--table)TABLE=$2 ; shift 2 ;;
-p|--port)
case "$2" in
"") PORT=1313; shift 2 ;;
*) PORT=$2; shift 2 ;;
esac;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
if [[ -z "$HOST" ]] || [[-z "$TABLE" ]] || [[ -z "$PORT" ]] ; then
usage()
exit
if
An alternative implementation using the getopts
shell builtin(this only supports small options):
while getopts ":h:p:t:" option; do
case "$option" in
h) HOST=$OPTARG ;;
p) PORT=$OPTARG ;;
t) TABLE=$OPTARG ;;
*) usage(); exit 1 ;;
esac
done
if [[ -z "$HOST" ]] || [[-z "$TABLE" ]] || [[ -z "$PORT" ]] ; then
usage()
exit
if
shift $((OPTIND - 1))
Further reading for GNU getopt and getopts bash builtin