I am trying to use getopt
to parse long arguments (some of which are compulsory and others that are not). The code:
#!/bin/bash
# firstName is compulsory, age is not and lastName is again compulsory.
OPTS=`getopt --long firstName:,age::,lastName: -n 'longArgumentsParsing' -- "$@"`
if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi
#echo "$OPTS"
eval set -- "$OPTS"
while true; do
echo "Argument seen: $1";
echo "And value seen: $2";
case "$1" in
--firstName ) echo "First name: $2"; shift 2;
;;
--lastName )
echo "Last Name: $2";
shift 2;
;;
--age ) if [ -z "$2" ];
then
echo "Age is not specified.";
else
echo "Age specifed: $2"; shift 2;
fi
;;
-- ) shift; break ;;
* ) break ;;
esac
done
Every time I run it with ./longArgumentsParsing --firstName sriram --age 30
the program exits with the following output:
Argument seen: sriram
And value seen: --lastName
The program is clearly unable to parse the input key and argument value pairs properly. Why? Where am I going wrong?
UPDATE:
As per this answer, I tried to debug this myself:
On the command line:
set -- --firstName sriram --lastName shankar
and then:
OPTS=$(getopt -l firstName:,lastName: -- "$@");
To get the output:
echo $?; echo "$OPTS"
0
'sriram' --lastName 'shankar' --
My questions:
1. How can I get the above to be correct?
2. I have removed the optional argument (which I do not want to do), and am still getting the error.