unrecognized option error: getopt command in shell

bash, getopt, shell

Solution

Disclaimer: this answer assumes you are using `getopt` from util-linux.

OK, this is not at all obvious, but you have to specify an optstring (IE a list of short options you want to accept). Assuming you don't want to accept any short options, just pass an empty string.

Here's the synopsis:

getopt optstring parameters
getopt [options] [--] optstring parameters
getopt [options] -o|--options optstring [options] [--] parameters

Note that optstring is required in all 3 forms.

Since you need to pass `-l`, you have to use one of the ones with options, so your call to getopt should be either:

getopt -n myscript -l a:,b:,cc:,dd:,ee:,ff:,gg:,hh: -- '' "$@"

or:

getopt -n myscript -l a:,b:,cc:,dd:,ee:,ff:,gg:,hh: -o '' -- "$@"

Problem

I'm new to shell and Linux, it would be great if someone can help me find what is wrong in the command: ``` if ! options=$(getopt -n myscript -l a:,b:,cc:,dd:,ee:,ff:,gg:,hh: -- "$@"); then exit 1; fi ``` I get an error msg: ``` mhagent: unrecognized option '--hh' options=' --aa '\''val1'\'' --ibb '\''val2'\'' --cc '\''val4'\'' --dd '\''val4'\'' --ee '\''val5'\'' --ff '\''val6'\'' --gg '\''val7'\'' --' ``` If I remove the last option: hh, it works fine. ``` if ! options=$(getopt -n myscript -l a:,b:,cc:,dd:,ee:,ff:,gg: -- "$@"); then exit 1; fi ```

Original source