Problem with getopts

I need to parse parameters but the arguments could be NULL,example:

> cat getopts.sh  
while getopts "a:b:" opt 2>/dev/null
do
    case "${opt}" in
      a)   echo "A:${OPTARG}" ;;
      b)   echo "B:${OPTARG}" ;;
      *)   exit 1 ;;
    esac
done

> getopts.sh -a TEST1 -b TEST2
A:TEST1
B:TEST2

> getopts.sh -a -b TEST2      
A:-b

The first posted execution of the script works fine , but i have a problem with the second one, getopts uses the -b parameter as the argument of the -a one :frowning:

How can i avoid this??

Thank u all in advance.

Try a quick fix!
if you MUST have "-a xx AND -b zz" on the command line then add this to your code.....

if [ $# != 4 ]
then
echo "Usage; `basename $0` -a value -b value'
exit 9
fi

while getopts "a:b:" opt 2>/dev/null
do
case "${opt}" in
a) echo "A:${OPTARG}" ;;
b) echo "B:${OPTARG}" ;;
*) exit 1 ;;
esac
done

> getopts.sh -a TEST1 -b TEST2
A:TEST1
B:TEST2

> getopts.sh -a -b TEST2
Usage; getopts.sh -a value -b value

Thank�s for the reply ,however that doesn't solve my issue.

The key point here is that i need a way to handle with NULL/NOT NULL arguments.
So, in the example previously posted , the result of:

getopts.sh -a -b TEST2 

Must be:

A:
B:TEST2

I know i can use other scripting tools , but i would like to do it with getopts.

Thank you all.

Cheers

Hi,
You can achieve the same without using getopts :

#!/usr/bin/bash

ARGUMENTS="a:b"
check_in_args()
{
	PAT=`echo ${ARGUMENTS} | awk -F: -v arg=$1 '{
			for(i=1;i<=NF;i++)
			{
				if("-" $i == arg)
				{
					printf("FOUND");
					break;
				}
			}
		}'`
	if [ "${PAT}" = "FOUND" ]
	then
		return 1
	else
		return 0
	fi
}

while [ $# -ne 0 ]
do
	case $1 in
	-a)
		check_in_args $2 RET
		if [ $? -eq 1 ]
		then
			A_VAL=""
		else
			A_VAL="$2"
			shift
		fi
	;;
	-b)
		check_in_args $2 RET
		if [ "${RET}" = "1" ]
		then
			B_VAL=""
		else
			B_VAL="$2"
			shift
		fi
	;;
	*)
	;;
	esac
	shift
done
echo "A:${A_VAL}"
echo "B:${B_VAL}"

Thanks
Raghu

NULL arguments are not a problem. This is how to do a NULL argument:

getopts.sh -a "" -b TEST2 

What you want is for a missing argument to be treated as NULL. Suppose that I want to run the script only using the -a option and I want the argument to the -a option to be "-b". This why "getopts.sh -a -b" must be treated the way it is. What I have sometimes done in cases like this is to use -a and -b which expect no arguments and -A and -B that demand an argument. The only other solution is to give up on getopts as Raghu suggested.

Thanks!! Perderabo for clarify me this question, and Thanks!! to Andrek and Raghu for the solutions.