Handling flags and optional parameters

suggest change

The getopts builtin can be used inside functions to write functions that accommodate flags and optional parameters. This presents no special difficulty but one has to handle appropriately the values touched by getopts. As an example, we define a failwith function that writes a message on stderr and exits with code 1 or an arbitrary code supplied as parameter to the -x option:

#  Fail with the given diagnostic message
# The -x flag can be used to convey a custom exit status, instead of
# the value 1.  A newline is automatically added to the output.

    local OPTIND OPTION OPTARG status


    while getopts 'x:' OPTION; do
        case ${OPTION} in
            x)    status="${OPTARG}";;
            *)    1>&2 printf 'failwith: %s: Unsupported option.\n' "${OPTION}";;

    shift $(( OPTIND - 1 ))
        printf 'Failure: '
        printf "$@"
        printf '\n'
    } 1>&2
    exit "${status}"

This function can be used as follows:

failwith '%s: File not found.' "${filename}"
failwith -x 70 'General internal error.'

and so on.

Note that as for printf, variables should not be used as first argument. If the message to print consists of the content of a variable, one should use the %s specifier to print it, like in

failwith '%s' "${message}"

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents