3

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.

Community
  • 1
  • 1
Sriram
  • 10,298
  • 21
  • 83
  • 136

1 Answers1

0

There are two issues in the above code:

  1. The script parses only long arguments. The correct invocation of getopt, in case one is using only long arguments is the following:

OPTS=$(getopt -o '' -l "firstName:,lastName:,age::" -- "$@");

Note the '' next to the -o flag. Getopt requires that the -o flag be left blank in case there are no short-form arguments.

  1. Arguments to this script need to be specified with the = sign.
    A sample invocation of the script would be:
    ./longArgumentsParsing.bash --firstName=sriram --lastName=shankar --age=30.
Sriram
  • 10,298
  • 21
  • 83
  • 136