1829453 Members
725 Online
109992 Solutions
New Discussion

getopts help

 
SOLVED
Go to solution
Pat Peter
Occasional Advisor

getopts help

Hi,

I am using the following script:

#!/usr/bin/ksh
program="${0:##*/}"

function usage {
echo "USAGE: $program [-d tardir -i instdir | -u]"
echo "d - message."
echo "i - message."
}


while getopts :d:i:u OPTION
do
case "$OPTION" in
d) tardir="$OPTARG";;
i) instdir="$OPTARG";;
u) usage;exit;;
:) print -u2 "$program: $OPTARG is missing argument!"
usage
exit 1;;
\?) print -u2 "$program: $OPTARG is an invalid option!"
usage
exit 1;;
esac
done
shift $(( $OPTIND - 1 ))


The issue is that I don't get any message when I just use:

"program"

I want it to give a message that arguments are needed to execute the program.

I get some message when I use an incorrect argument.

Please help.

Thanks,
Pat
2 REPLIES 2
curt larson_1
Honored Contributor

Re: getopts help

getopts doesn't test for required options.

you'll need to test for that yourself. something like this:

tardir=
instdir=

while getopts :d:i:u OPTION
do
.
.
.
done

if [ -z "$tardir" ] ;then
print -u2 "$program: tardir is unspecified"
usage
exit 2
fi

probably best to test for the existance of the directories also, [ ! -d "$tardir" ]
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: getopts help

There are several ways to do this but most common is to simply test ${#} after the ${OPTIND} shift at the end of the getopts processing case statement.

e.g.
if [[ ${#} -lt 1 ]]
then
echo "Required arguments missing" >&2
exit 255
fi


When multiple arguments are required one technique is to initialize a flag variable to zero and then set this flag variable to non-zero in the getopts case statement. At the end of the case, you make sure that all of these corresponding flag variables are non-zero.
If it ain't broke, I can fix that.