Processing Options in Bash

From Zanecorpwiki

Jump to: navigation, search

I love the bash option processing. It's straightforward and is true to the standard. Try wrapping non-bash scripts in a bash script that process and regularize options for the underlying script.

TMP=`getopt --name=$0 -a --longoptions=foo:,bar -o f:,b -- $@`
eval set -- $TMP

until [ $1 == -- ]; do
    case $1 in
        -f|--foo)
            FOO=$2 # option param is in position 2
            shift;; # remove the option's param
        -b|--bar)
            BAR=1;; # no parameter taken by the bar option
    esac
    shift # move the arg list to the next option or '--'
done
shift # remove the '--', now $1 positioned at first argument if any

The ':' indicates the option takes a parameter. ';' indicates that a parameter is optional. Must provide at least one short option (after -o).

Personal tools