Skip to content

Instantly share code, notes, and snippets.

@caruccio
Last active November 3, 2023 22:07
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save caruccio/836c2dda2bdfa5666c5f9b0230978f26 to your computer and use it in GitHub Desktop.
Save caruccio/836c2dda2bdfa5666c5f9b0230978f26 to your computer and use it in GitHub Desktop.
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=true, help=false, log=debug
Found 3 arguments: hello cruel world
@italovieira
Copy link

In the last example force should be true.

@caruccio
Copy link
Author

caruccio commented Jul 1, 2022

Thanks @italovieira

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment