DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Getopts

07.06.2007
| 11921 views |
  • submit to reddit
        // Example to use getopts in shell scripts

#!/bin/sh

usage()
{
        echo "Usage: $0 -c -d -e -a all -b ball";
        exit 1;
}

if [ $# -lt 1 ] ; then
        usage;
fi

# ":" decides which options require an argument
# In the example below options "a" and "b" will require a value to be passed along
while getopts a:b:cde opt
do
        case "$opt" in
                a) echo "hello $OPTARG";;
                b) echo "hello $OPTARG";;
                c) echo "c is selected";;
                d) echo "d is selected";;
                e) echo "e is selected";;
                \?) usage;;
        esac
done