bash getopts

If you’re scripting with bash, and haven’t encountered the getopts function, then you should read the following
article @ linux.com.

The getopts function is an -easy to use- function when you’re working with script where parameters and flags have to be set.

Example

while getopts ":f:p:c:s:d r v" o ; do
        case $o in
                f ) FILE=$OPTARG;;
                p ) PARA=$OPTARG;;
                c ) VALU=$OPTARG;;
                s ) DELI=$OPTARG;;
                d ) DEBUG=y;;
                r ) RO=y;;
                v ) echo $VERSION
                    exit 0;;
        esac
done

The options with a colon (“:”) in front of them need to have an argument set. Yet if there is a space, then no argument is needed.

So -r -d & -v are the flags. Where the others are options/parameters that can be set.

5 thoughts on “bash getopts

  1. You say “The options with a colon (”:”) in front of them need to have an argument set” and then you say “So -r -d & -v are the flags” yet the code example has a colon in front of the d. So then really only r and v can be used without an argument correct?

  2. It should say “the options with a colon *after* them need to have an argument.”
    The colon in front of the string turns off error-messages.

    Cheers,
    Daniel

  3. After the final done you need a
    shift $((OPTIND -1)) or else a “$@” will re-use the options already handled by the getopts.

  4. i have the following scenario want to run the following script with manadory and optional argumnets

    Manadory options are :

    filename=””
    port=””
    optional arguments

    type -t [A/B]
    balances -b bal
    prices -p

    ./test filename port -t A -b bal

    my code i have that won’t parse the options is
    This is what i have
    #!/bin/bash
    filename=””
    port=””

    while getopts b:t:p opt
    do
    case $opt in
    b) BAL=”${OPTARG}”
    if [ “$BAL” == “” ]
    then
    print_usage $0
    else
    echo “Balances is ” $BAL
    fi ;;

    t) TYPE=”$OPTARG”;;
    p) PRICES=”$OPTARG”;;
    ?) print_usage $0
    exit 1;;
    esac
    done
    echo “Balances: “$BAL
    echo “Type: “$TYPE

    Any ideas why this won’t work for me ?????
    ~

Leave a Reply to David Dreggors Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.