getopts

Syntax:
getopts option_list variable_name [argument list]
The variable_name is user defined. The argument_list is usually the current parameter list $* or $@.

Example

The option_list of abc:de

Would describe the following combinations:

script -a -b -c arg -d -e
script -abc arg -de
script -abde -c arg
script -e -d -b -a -c arg
script -c arg -abde
script -c arg -a -b -d -e


Example 2

#!/usr/bin/sh

while getopts ab flag
do
    case $flag in
        a) print "a option" ;;
        b) print "b option" ;;
    esac
done
Try running the previous example with the -a -b and -? options.

Example 3

Let's add some lines to the script. Don't forget the colon in front of the option list.
#!/usr/bin/sh

while getopts :ab flag
do
    case $flag in
        a) print "a option" ;;
        b) print "b option" ;;
        \?) print "INVALID option"
            print "     usage: $0 [ -a -b ] " ;;
    esac
done

Example 4

Let's add some lines to the script. Don't forget the c and the colon at the end of the option list.
#!/usr/bin/sh

while getopts :abc: flag
do
    case $flag in
        a) print "a option" ;;
        b) print "b option" ;;
        c) print "c option with argument $OPTARG" ;;
        \?) print "INVALID option"
            print "     usage: $0 [-a] [-b] [-c arg] " ;;
    esac
done

Example 5

Let's add some lines to the script. Don't forget the d and the colon at the end of the option list.
#!/usr/bin/sh

while getopts :abc:d: flag
do
    case $flag in
        a) print "a option" ;;
        b) print "b option" ;;
        c) print "c option with argument $OPTARG" ;;
        d) print "d option with argument $OPTARG" ;;
        \?) print "INVALID option"
            print "     usage: $0 [-a] [-b] [-c arg] [-d arg]" ;;
    esac
done
Try running the previous script like this:

     $ ./getopts.sh -a -b -c hello -d world happy joy joy
What happened?

Example 6

Let's add some lines to the script.
#!/usr/bin/sh

while getopts :abc:d: flag
do
    case $flag in
        a) print "a option" ;;
        b) print "b option" ;;
        c) print "c option with argument $OPTARG" ;;
        d) print "d option with argument $OPTARG" ;;
        \?) print "INVALID option"
            print "     usage: $0 [-a] [-b] [-c arg] [-d arg] arg arg..." ;;
    esac
done

shift $((OPTIND - 1 ))

while (( $# > 0 ))
do
    print "next arg is $1"
    shift
done