Public feed #600475

getopts example

public shellscript v1 · immutable
Raw Edit
·published 2007-07-02 21:45 UTC
rendered paste body
#  getopts has some problems. If an argument is given at the command line with-#+ out the OPTARG, getops skips it altogether.#  For example, if -e is passed without a subsequent value, e) is not processed.#  On the other hand, if -e -b is passed, $ENV=$OPTARG="-b", not the right type#+ of behaviour.#  That being said, getops default behaviour for missing/bad arguments is to #+ throw an error or default to *). The default behaviour is being suppressed#+ by the prefixed ":" (getopts ":...") Therefore, the sanity checks are after#+ the getops/case structure.while getopts ":e:b:c:q:pPdhl" MyOpts ; do        case $MyOpts in  # case v. if: mein kampf        e) # Environment                ENV=$OPTARG        ;;        b) # Branch                BRANCH=$OPTARG        ;;        c) # Component                COMP=$OPTARG        ;;        p) # Yes `p4 sync`                P4SYNCY="Y"        ;;        P) # No `p4 sync`                P4SYNCN="Y"                #  Cannot reuse P4SYNCY, otherwise the sanity check                #+ below could not be made.        ;;        q) # Specify QS build type                QSOPT=$OPTARG        ;;        d)                DEBUG="Y"        ;;        l) # Label p4                LABELPERFORCE="Y"        ;;        \? | h) # Help!                usage                exit 0        ;;#       *) # Bad args.#               usage#               exit $ERR_BADARGS#       ;;        esac    # --- END of case $MyOpts in ---done # --- END of while getops ---