Parsing parameters in bash – a getopt template

Writing some bash scripts that parse command lines, I wrote this handy template with getopt. It is easy to apply even for simplest scripts.

OPTION_SPEC="help,flag1,flag2_params:"
PARSED_OPTIONS=$(getopt -n "$0" -a -o h --long $OPTION_SPEC -- "$@")
OPTIONS_RET=$?
eval set -- "$PARSED_OPTIONS"

Parsing error or no flags

if [ $OPTIONS_RET -ne 0 ] || [ $# -le 0 ]; then usage; die; fi

while [ $# -ge 1 ]; do case $1 in --help | -h ) usage; die;; --flag1 ) FLAG1=1;; --flag2_params ) shift; FLAG2_PARAMS="$1";; -- ) shift;; * ) echo "ERROR: unknown flag $1"; usage; die;; esac shift done

No more unannotated $ns in my scripts!

One Response to “Parsing parameters in bash – a getopt template”

  1. sohbet Says:

    Thanks.

Leave a Reply