Wednesday, August 25, 2010

Getopts in Bash shell Scripts

### Example of Getopts ###

Getopts Multi Option Parsing ...
01    #!/bin/bash    // Run time parameters
02   
03    function help {
04        echo "Usage: test -p"
05    }
06   
07    if test $# -eq 0; then
08        help
09        exit 0
10    fi
11   
12    exit 0

If you don't give any parameters, it prints the help message. But... what about checking the parameter itself? Thats where getopts comes into play! First of all, look at the following script, which adds the getopts to the above script...

01    #!/bin/bash
02   
03    function help {
04        echo "Usage: test -p"
05    }
06   
07    if test $# -eq 0; then
08        help
09        exit 0
10    fi
11   
12    while getopts "p" option; do
13        case $option in
14            p) echo "this is a test";;
15            *) help;;
16        esac
17    done
18   
19    exit 0

#### How it works

Each time the while loop is executed, getopts puts the next parameter into the variable option. The parameters desired, must be defined as a string, containing them one by one.

If you want to accept the parameters a, b, and c, the loop should be:

while getopts  "abc" var; do
2        case $var in
3            a) echo "parameter a given";;
4            b ) echo "parameter b given";;
5            c) echo "parameter c given";;
6            *) echo "Usage: script -abc";;
7        esac
8    done

### Accepting Arguments   
Getopts gives you a way to accept arguments for a parameter too! Just put a  :  after the parameter's name. Like this:

1    while getopts "a:bc"  var; do
2        case $var in
3            a) echo "parameter a given, it's argument is $OPTARG";;
4            b ) echo "parameter b given";;
5            c) echo "parameter c given";;
6            *) echo "Usage: script -a message -bc";;
7        esac
8    done

As understood from above script, the corresponding argument for a parameter is inside the variable OPTARG. So, you can easily manage it
  

No comments: