2

I followed the posts on stackexchange websites to parse command line arguments. My program only parses long arguments and all arguments are mandatory. Here is what I have done:

getopt --test > /dev/null if [[ $? -ne 4 ]]; then echo "getopt --test failed in this environment." exit 1 fi function quit { echo "$1" exit 1 } # Option strings LONG="producer-dir:,consumer-dir:,username:,password:,url:,kafka-host:,checkpoint-dir:" # read the options OPTS=$(getopt --longoptions ${LONG} --name "$0" -- "$@") if [ $? != 0 ]; then quit "Failed to parse options...exiting." fi eval set -- "$OPTS" # extract options and their arguments into variables. while true ; do case "$1" in --producer-dir ) PRODUCER_DIR="$2" shift 2 ;; --consumer-dir ) CONSUMER_DIR="$2" shift 2 ;; --username ) USERNAME="$2" shift 2 ;; --password ) PASSWORD="$2" shift 2 ;; --url ) URL="$2" shift 2 ;; --kafka-host ) KAFKA_HOST="$2" shift 2 ;; --checkpoint-dir ) CHECKPOINT_DIR="$2" shift 2 ;; -- ) shift break ;; *) echo "Internal error!" exit 1 ;; esac done 

No matter in which order I pass the arguments, the first one is ignored and the result is empty. The rest of the arguments are parsed as expected. What am I missing?

1 Answer 1

6

I think what is happening is that what you intend to be your first parameter is being interpreted by getopt as an optstring. The beginning of the getopt man page lists three synopses. You seem to be using the second:

`getopt [options] [--] optstring parameters` 

Notice how after the -- the first item is not parameters, but optstring.

While we're at it, I should mention that bash has an internal version of getopt, called getopts with the trailing s. All other things being equal, using bash's internal feature should be more efficient.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.