getopts in shell script

Thursday, July 14, 2011

getopts
The getopts command simplifies the task of validating and parsing command line options and arguments for your shell scripts.

Syntax:


getopts <optstring name> [arg...]

Example:


Step1: First I define all my option holding variables.

ListFiles=0
MoveFiles=0
email=""


Step2: While loop.

The following while statement loops through all the options and sets them to the corresponding variable. getopts returns true while there are options to be processed. The argument string, here "lme:h", specifies which options the script accepts. If the user specifies an option which is not in this string, it will go into * section which will display a help to use this script with examples. If the option is succeeded by a colon, the value immediately following the option is placed in the variable $OPTARG.


while getopts "lme:h" option; do
case "$option" in
l) ListFiles=1;;
m) MoveFiles=1;;
e) email="$OPTARG";;
h|*) helpFunction;;
esac
done

Script Call:
-----------------------------------------------------------------------------------------------------------------------------------------------
ExampleScript.sh -l

#It will go into case l) and set ListFiles=1.

ExampleScript.sh -m
#It will go into case m) and set MoveFiles=1.

ExampleScript.sh -m -e "example@gmail.com"
#It will go into case m) and e) and set MoveFiles=1 as well as get the email address in $Ovariable and set it to "email" variable.

ExampleScript.sh -h
#It will go into case h|*) and call the function helpFunction to show help.

ExampleScript.sh -<anything apart from optstringname we have provided>
#It will also go into case h|*) and will be treated as "*" and show the help.
------------------------------------------------------------------------------------------------------------------------------------------------


Comments/suggestions are welcome.. Happy scripting ... :)
 
Related Posts Plugin for WordPress, Blogger...

0 comments:

Post a Comment

 
© Copyright 2010-2012 Learn MySQL All Rights Reserved.
Template powered by Blogger.com.