Radyum
Radyum

Reputation: 101

Getopt parsing error in bash script (option declaration mistake)

I need to get 4 options (each with a short and a long version) in a bash script.

Here is what I did:

OPTS=`getopt -l :author,icon,channel,message: -o :aicm: -- "$@"` || 
exit 1
eval set -- "$OPTS"
while true; do
    case "$1" in
    -a|--author) echo "A:'$2'"; shift;;
    -i|--icon) echo "I:'$2'"; shift 2;;
    -m|--message) echo "M:'$2'"; shift 2;;
    -c|--channel) echo "C:'$2'"; shift 2;;
    --) shift; break;;
    *) echo Error; exit 1;;
    esac
done

And here is what I get:

command

docker run --rm -e SLACK_TOKEN slacker notify --channel foo

output

C:'--'
Error

Of course, I would like to have this output:

C:'foo'

Upvotes: 0

Views: 178

Answers (1)

larsks
larsks

Reputation: 311406

Your getopt command looks a little funky. You seem to be using : as some sort of delimiter, here:

-l :author,icon,channel,message: 

And here:

-o :aicm:

That doesn't make any sense. The : has special meaning in the options definitions; take a look at the getopt(1) man page:

-l, --longoptions longopts

The long (multi-character) options to be recognized. More than one option name may be specified at once, by separating the names with commas. This option may be given more than once, the longopts are cumulative. Each long option name in longopts may be followed by one colon to indicate it has a required argument, and by two colons to indicate it has an optional argument.

The same is true of short options.

So assuming that all of your options take arguments, you would write:

OPTS=`getopt -l author:,icon:,channel:,message: -o a:i:c:m: -- "$@"` || 

Upvotes: 1

Related Questions