Skip to content

Instantly share code, notes, and snippets.

@caruccio

caruccio/getopts.md

Created Apr 9, 2019
Embed
What would you like to do?
Read shell options with positional arguments

This example shows how to read options and positional arguments from a bash script (same principle can be applied for other shells).

# some global var we want to overwrite with options
force=false
help=false
log=info
ARGS=() ### this array holds any positional arguments, i.e., arguments not started with dash

while [ $# -gt 0 ]; do
    while getopts fhl: name; do
        case $name in
            f) force=true;;
            h) help=true;;
            l) log=$OPTARG;;
        esac
    done
    [ $? -eq 0 ] || exit 1
    [ $OPTIND -gt $# ] && break   # we reach end of parameters

    shift $[$OPTIND - 1] # free processed options so far
    OPTIND=1             # we must reset OPTIND
    ARGS[${#ARGS[*]}]=$1 # save first non-option argument (a.k.a. positional argument)
    shift                # remove saved arg
done

echo Options: force=$force, help=$help, log=$log
echo Found ${#ARGS[*]} arguments: ${ARGS[*]}

Examples:

$ ./read-args 
Options: force=false, help=false, log=info
Found 0 arguments:

$ ./read-args -f
Options: force=true, help=false, log=info
Found 0 arguments:

$ ./read-args -f -h -l debug
Options: force=true, help=true, log=debug
Found 0 arguments:

$ ./read-args -f -h -l debug hello
Options: force=true, help=true, log=debug
Found 1 arguments: hello

$ ./read-args hello -f cruel -l debug world
Options: force=false, help=false, log=debug
Found 3 arguments: hello cruel world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment