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
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.