Unix Shell - ksh getopts - Either / OR parameter

This is Interesting: Free IT Magazines  
Home > Archive > Unix Shell > October 2005 > ksh getopts - Either / OR parameter





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author ksh getopts - Either / OR parameter
da

2005-10-31, 5:58 pm

Hi,

I have a ksh program which gets a few parameters using getopts.

Is there any way I can mandate, the user passes only one of the two
parameters?

ex,

myprog.ksh [-f <file>] [-N name | -n id]

I want the user to pass either -N or -n, but not both. either one of -N
or -n is a required parameter.

Thanks.

Ed Morton

2005-10-31, 5:58 pm

da wrote:

> Hi,
>
> I have a ksh program which gets a few parameters using getopts.
>
> Is there any way I can mandate, the user passes only one of the two
> parameters?
>
> ex,
>
> myprog.ksh [-f <file>] [-N name | -n id]
>
> I want the user to pass either -N or -n, but not both. either one of -N
> or -n is a required parameter.
>
> Thanks.
>


Yes, put this within your while getopts loop:

case "$arg" in
....
n) if [ -z "$name" ]; then
id="$OPTARG"
else
echo "error"
exit 1
fi
;;
N) if [ -z "$id" ]; then
name="$OPTARG"
else
echo "error"
exit 1
fi
;;
....
esac

and this after it:

if [ -z "$id" -a -z "$name" ]
then
echo "error"
exit 1
fi

Obviously you may want to get a tad more expressive with the error
messages, add a "usage", etc....

You may also want to consider what to do if the user uses the same
argument twice, e.g.:

myprog.ksh -n this -n that

Regards,

Ed.
da

2005-10-31, 5:58 pm

Thanks Ed,

> Obviously you may want to get a tad more expressive with the error
> messages, add a "usage", etc....


I do have the usage(), which explains each parameters and the usage
etc.


Ed Morton wrote:
> da wrote:
>
>
> Yes, put this within your while getopts loop:
>
> case "$arg" in
> ....
> n) if [ -z "$name" ]; then
> id="$OPTARG"
> else
> echo "error"
> exit 1
> fi
> ;;
> N) if [ -z "$id" ]; then
> name="$OPTARG"
> else
> echo "error"
> exit 1
> fi
> ;;
> ....
> esac
>
> and this after it:
>
> if [ -z "$id" -a -z "$name" ]
> then
> echo "error"
> exit 1
> fi
>
> Obviously you may want to get a tad more expressive with the error
> messages, add a "usage", etc....
>
> You may also want to consider what to do if the user uses the same
> argument twice, e.g.:
>
> myprog.ksh -n this -n that
>
> Regards,
>
> Ed.


Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com