Computing.Net > Forums > Unix > getopts command

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Click here to start participating now! Also, check out the New User Guide.

getopts command

Reply to Message Icon

Name: ceeeeeej
Date: January 1, 2003 at 04:05:45 Pacific
OS: win98
CPU/Ram: PIII 667Mhz, 192MB
Comment:

i just learned that when you use getopts, the argument after an option is stored in $OPTARG variable.

how about if i have more than 1 arguments? if i'm not mistaken, $OPTARG gets 1 only. how can i get the other arguments?



Sponsored Link
Ads by Google

Response Number 1
Name: James Boothe
Date: January 4, 2003 at 07:26:36 Pacific
Reply:

Correct, only one argument at a time is stored in $OPTARG. getopts needs to be ran within a loop, and each execution of getopts will process just one option:

#!/bin/ksh

optiona=n
optionb=n
optionc=n

while getopts d:u:abc opt
do
print "opt=$opt OPTARG=$OPTARG"

case $opt in
d) database=$OPTARG;;
u) username=$OPTARG;;
a) optiona=y;;
b) optionb=y;;
c) optionc=y;;
*) print "Valid syntax is ..."
exit;;
esac

done

shift $((OPTIND -1))

print "\nProcessing options are:"
print "database=$database"
print "username=$username"
print "option a: $optiona"
print "option b: $optionb"
print "option c: $optionc"
print "files to be processed: $*"

exit 0

And following is a sample execution. Note that after shifting the parameters out of the way, this leaves only the filenames on the command line:

myscript -dPROD1 -uJBoothe -ac file1 file2 file3
opt=d OPTARG=PROD1
opt=u OPTARG=JBoothe
opt=a OPTARG=
opt=c OPTARG=

Processing options are:
database=PROD1
username=JBoothe
option a: y
option b: n
option c: y
files to be processed: file1 file2 file3


0
Reply to Message Icon

Related Posts

See More


comparing time... please ... such .sed file?



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: getopts command

lp -c command www.computing.net/answers/unix/lp-c-command/6568.html

Batch command www.computing.net/answers/unix/batch-command/6951.html

getopts for bourne www.computing.net/answers/unix/getopts-for-bourne/4852.html