getopts

Lars Kellogg-Stedman lars at larsshack.org
Wed Jan 30 15:14:45 EST 2002


> #!/bin/sh
> #
> #       Handles Arguments
> #
> 
> while getopts xy: option

The first problem is with you optstring.  If both the 'x' and 'y' 
options require an argument (which is what your help text implies), then 
your optstring should be 'x:y:'.

> echo $OPTARG

What's this echo statement doing in the expression portion of your while 
statement?  I think you meant for this to come after the 'do' on the 
next line.  The way its current positioned, your while statement looks 
like this:

   while true; do

Which would loop forever, except that getopts sets option to '?' if 
there are no more arguments, so instead it bails out in your case statement.

> do
>         case $option in
>                 x) xdim=$OPTARG;;
>                 y) ydim=$OPTARG;;
>                 \?) echo "usage: ds9sh [-x columns] [-y columns] file..."
>                 exit 2;;
>         esac
> done
> shift `expr $OPTIND - 1`

This ought to work for you:

   while getopts x:y: option; do
     case $option in
       x) xdim=$OPTARG;;
       y) ydim=$OPTARG;;
       \?) echo "usage: ..."
           exit 2;;
     esac
   done
   shift `expr $OPTIND - 1`

Note that I've replaced some EOLs with semicolons, which is just my 
formatting preference.  The following two statements are equivalent:

   while true; do
     echo hello
   done

And:

   while true
   do
     echo hello
   done

-- Lars




More information about the Discuss mailing list