getopt

#!/bin/sh

set -- `getopt "abco:" "$@"`

a= b= c= o=
while :
do
    case "$1" in
    -a) a=1;;
    -b) b=1;;
    -c) c=1;;
    -o) shift; o="$1";;
    --) break;;
    esac
shift
done
shift # get rid of --
# rest of script...
# e.g.
ls -l $@

This code works well until there are filenames with spaces, even getopt -s sh doesn't help. How this problem could be resolved?

space are evil. the easy way to to prevent them by quoting on the commandline.

This wil not help as far as quoting will be removed by getopt

hi all...

i have come across the posting ....
can any one please explain the code..

set -- `getopt "abco:" "$@"`

a= b= c= o=
while :
do
case "$1" in
-a) a=1;;
-b) b=1;;
-c) c=1;;
-o) shift; o="$1";;
--) break;;
esac
shift
done
shift # get rid of --
# rest of script...
# e.g.
ls -l $@

.....

what will set -- `getopt "abco:" "$@"` do and so on.

$@ is all positional parameters, i.e. if you execute command attr0 attr1 then $@ is equal to attr0 attr1

The Bourne Shell set command sets positional parameters to the getopt's output, i.e. if getopt returns something like -a -b -- test then $@ will be equal to -a -b -- test

Note: '--' is used in set command to resolve problems with parameters that begins with '-' character

In while loop positional parameters are being processed till '--' ($1 refers to first positional parameter, shift deletes first positional parameter)

Thanks a lot....

With KSH you can use getopts :

#!/bin/ksh

while getopts abco: name
do
   case $name in
      a)  a=1;;
      b)  b=1;;
      c)  c=1;;
      o)  o="$OPTARG";;
   esac
done

shift $(($OPTIND -1))
# rest of script...
# e.g.
ls -l $@

jean-Pierre.