Looping through arguments that are passed into a bash script

#Function that provides the user with useage instructions

useage()

{

        echo ---------------Useage-----------------------------

                echo "Useage: $0 -a foo -b bar"

                echo "eg: $0 -a asdf -b fdas"

        echo --------------------------------------------------

}

#If the number of arguments is zero quite and advise on useage

if [ $# -eq 0 ]

    then

    useage

    exit 1

fi

#While the number of arguments is greater than zero we will loop through them #and look for the flag $1 (first argument). From there we assign the value #given for that flag $2 (the one beside $1 in the $# list). We then use the #shift command to progress further into the $# list, then we rinse and #repeat.

#The -* catches users not using the correct flag eg -a and not -d and the * #is a big net that catches everything else other then what should have been #supplied as an argument.

while [ $# -gt 0 ]

do

        case $1 in

                -a)

                a=$2; shift;;

                -b)

                b=$2; shift;;

                -*)

                useage

                exit 1;;

                *)

                useage

                exit 1;;

        esac

        shift

done

Advertisements

Leave a 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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s