Saturday 13 December 2008

getopts utility

Here is an easy command to run a shell script with options and arguments on the command line with out writing lengthy code..

For example,If i want to run a shell script netdep.sh with options of version file, configfile and ips to give in command line..
"getopts" gives the best way of doing it as shown with while:

while getopts v:c:i: option
do
case "$option" in
v) versionfile="$OPTARG";;
c) configfile="$OPTARG";;
i) ips="$OPTARG" ;;
[?]) "Usage: `basename $0` -v [versionfile] -c [configfile] -i [list of ips]"
exit $NOARGS;;

esac

done

with this my script can run like this:

./run.sh -v latest.xml -c abc.conf -i 172.22.21.39

Explanation :
v:c:i: - A colon symbol is used for every option implies that all the three options v,c and i expect an argument after mentioning them.
OPTARG is a getopts variable which stores the arguments given in the command line sequentially.


For quick walk through shell-scripting look into :

http://steve-parker.org/sh/sh.shtml



No comments:

Post a Comment

Tweets by @sriramperumalla