[Ilugc] Re: [Shell Code ] Use of getopts

  • From: subhojit.ojha@xxxxxxxxx (subhojit ojha)
  • Date: Fri Apr 23 12:46:41 2010

Thanks to all of you for providing such wonderful examples.....
sorry for top posting

Regards
Subhojit Ojha

On Thu, Apr 22, 2010 at 12:19 AM, Mohan R <mohan43u@xxxxxxxxx> wrote:

Hi,

And here is the shell code,



[parseoptions.sh]
#!/bin/sh
# script to parse options using getopts

while getopts 'ab:' OPTION
do
       case "${OPTION}"
       in
               a) echo "-a supplied";;
               b) echo "-b supplied with '${OPTARG}'";;
               *) echo "Wrong option '${OPTION}' supplied";;
       esac
done
shift $((OPTIND - 1))
echo "Remaining Arguments '${@}'"


$ ./parseoptions.sh -a -b apple orange banana
-a supplied
-b supplied with 'apple'
Remaining Arguments 'orange banana'
$





[parseoption.sh]
#!/bin/sh
# script to parse options using getopt

PARSEDOPTIONS=$(getopt -o 'ab:' --longoptions 'long-x,long-y,long-z:' --
"${@}")
set -- ${PARSEDOPTIONS}
while test "${1}" != "--"
do
       case "${1}"
       in
               -a) echo "-a supplied"; shift;;
               -b) echo "-b supplied with ${2}"; shift 2;;
               --long-x) echo "--long-x supplied"; shift;;
               --long-y) echo "--long-y supplied"; shift;;
               --long-z) echo "--long-z supplied with ${2}"; shift 2;;
               *) echo "Wrong option ${1} supplied"; shift;;
       esac
done
shift
echo "Remaining arguments ${@}"


$ ./parseoption.sh -a -b apple --long-x --long-y --long-z orange banana
-a supplied
-b supplied with 'apple'
--long-x supplied
--long-y supplied
--long-z supplied with 'orange'
Remaining arguments 'banana'
$



And finally, one of the key difference between these two is, 'getopts' is
POSIX shell built-in, where 'getopt' is a separate executable living inside
'/usr/bin/'. Another difference is, 'getopts' cannot parse options like
'--big-option' whereas 'getopt' can.

I hope above examples will help you to understand getopts and getopt. Its a
standard practice to parse options inside your shell script using
getopts/getopt. Please read 'man getopt' and 'man sh'(then search for
getopts) for reference.

Thanks,
Mohan R.


_______________________________________________
ILUGC Mailing List:
http://www.ae.iitm.ac.in/mailman/listinfo/ilugc

Other related posts: