Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 11 May 1997 08:51:46 -0800 (AKDT)
From:      Steve Howe <un_x@anchorage.net>
To:        freebsd-questions <questions@freebsd.org>
Subject:   getopts
Message-ID:  <Pine.BSF.3.95q.970511082828.18804A-100000@aak.anchorage.net>

next in thread | raw e-mail | index | archive | help

ok - i finally figured this out, and am posting my answer
for anyone else that may be interested ...  there are a few
tricky aspects of it (w/thanks to zgabor).
-------------------------------------------------------------------------
while getopts abc i; do
	case $i in
		a)	a=$i; echo A;;
		b)	b=$i; echo B;;
		c)	c=$i; echo C;;
		?)	e=$i; echo huh?;;
	esac
done
shift $(($OPTIND - 1))
echo $a + $b + $c
echo $0 $1
-------------------------------------------------------------------------
this script may be invoked as
"script -abc   file" or
"script -bc -a file" or
"script -c -cc file" ... (C will echo 3x)

the "shift" statement MUST occur
as above, or any "file" will not
appear in "$1" when option parsing
is done.  you CANNOT replace the
"shift" statement above with

"a) a=$i; echo A; shift;;"

type case statements, otherwise

"script -abc file"

where "-abc" is "$1"
will get shifted 3x, and
you will lose "file".

any number of options in the getopts statement
may be followed by a colon, in which case,
$OPTARG will contain the options argument,
which should be "caught" by its corresponding
options "case" statement.

the "e" case statement will trap any errors.

i don't know if "getopts" can be used
without a "while" statement ...




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.BSF.3.95q.970511082828.18804A-100000>