Saturday, January 15, 2011

Bash getops - Quick & Easy

Ever wanted to create this super script with tonns of flags and parameters?
In this short tutorial I will show you how to do it in bash shell.

Let's say we have a script
That has 3 flags (-v for verbouse, -h for help, -i for ip address as input).
The two first parameters do not really get input, but more "tell the script how to behave", while the third parameter actually gets a value from user (ip address).

The "getopts" function is a very handful function when you’re working with script where parameters and flags have to be set.

Our script will be executed as (for example):
#./ -v -i

This is the content of our short script:
usage() {
cat << EOF
-h help
-v verbouse mode
-i new ip address
while getopts "i:hv" flag ; do
        case $flag in
                i ) IPADDR=$OPTARG;;
                h ) usage;;
                v ) VERB=1;exit 0;;
Pay attention to the options with a colon (“:”) after them need to have an argument set.
Yet if there is no column, then no argument is needed (-h, -v).

We combine while loop with "getopts" function, that will use case to determine which flags were used and what values has been assigned.

1 comment:

M. said...

aint that not better?

h ) usage; exit 0;;
v ) VERB=1;;