Re: Help with "getopts"
- From: Douglas O'Neal <oneal@xxxxxxxxxxxx>
- Date: Wed, 29 Aug 2007 12:55:46 -0400
Rich Leitner wrote:
I'm writing some shell scripts and trying desperately to understand "getopts", specifically it's intrinsic variable $OPTIND. The guidance I've seen so far seems straightforward enough but then just doesn't seem to jibe with what I actually see when using it. What exactly is $OPTIND counting? There 'seems' to be a pattern, but every time I think I've figured out what it is, it 'breaks' for another form of calling a script. Here's an example ... a simple shell script called 'optscript':
#!/bin/bash
while getopts "abc:def:ghi" flag
do
echo "flag: $flag" "OPTIND: $OPTIND" "OPTARG: $OPTARG"
done
Now the various outputs:
bash>./optscript -abc charlie
flag: a OPTIND: 1 OPTARG: flag: b OPTIND: 1 OPTARG: flag: c OPTIND: 3 OPTARG: charlie
bash>./optscript -a -b -c charlie
flag: a OPTIND: 2 OPTARG: flag: b OPTIND: 3 OPTARG: flag: c OPTIND: 5 OPTARG: charlie
bash>./optscript -abc charlie -def foxtrot
flag: a OPTIND: 1 OPTARG: flag: b OPTIND: 1 OPTARG: flag: c OPTIND: 3 OPTARG: charlie
flag: d OPTIND: 3 OPTARG: flag: e OPTIND: 3 OPTARG: flag: f OPTIND: 5 OPTARG: foxtrot
bash>./optscript -a -b -c charlie -d -e -f foxtrot
flag: a OPTIND: 2 OPTARG: flag: b OPTIND: 3 OPTARG: flag: c OPTIND: 5 OPTARG: charlie
flag: d OPTIND: 6 OPTARG: flag: e OPTIND: 7 OPTARG: flag: f OPTIND: 9 OPTARG: foxtrot
Can anyone tell me what actually causes $OPTIND to increment up one (or two), and what causes it to stay the same? Thanks ...
Rich Leitner
OPTIND is set to the index of the next argument to be processed
(straight from the man page). For your first example, -abc is
index 1 and charlie is at index 2. First invocation processes
argument "a" and OPTIND is kept at 1 since there is more to be
processes at that position. Second invocation processes "b" and
still keep OPTIND at 1. Third invocation processes "c" and pulls
in "charlie" as the option argument. OPTIND is then set to be
3 to go one past "charlie".
Second example: process "-a", set OPTIND to 2 so -b can be
processed next. Process -b, set OPTIND to 3 so -c can be
processed next. Process -c and pull in "charlie", set OPTIND
to 5, one past "charlie".
Every time you finish with all the arguments at a given position
in the command line, increment OPTIND to point to the next
unprocessed argument.
Doug
.
- Follow-Ups:
- Re: Help with "getopts"
- From: Rich Leitner
- Re: Help with "getopts"
- References:
- Help with "getopts"
- From: Rich Leitner
- Help with "getopts"
- Prev by Date: Help with "getopts"
- Next by Date: Re: Help with "getopts"
- Previous by thread: Help with "getopts"
- Next by thread: Re: Help with "getopts"
- Index(es):
Relevant Pages
|