getopts in shell script

Thursday, July 14, 2011

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


getopts <optstring name> [arg...]


Step1: First I define all my option holding variables.


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;;

Script Call:
----------------------------------------------------------------------------------------------------------------------------------------------- -l

#It will go into case l) and set ListFiles=1. -m
#It will go into case m) and set MoveFiles=1. -m -e ""
#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. -h
#It will go into case h|*) and call the function helpFunction to show help. -<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...


Post a Comment

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