Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

option requires an argument error

Tags:

bash

shell

I wrote a shell script to do something. Everything works fine! A part of my code is something like this, so that I can pass options and arguments to it:

while getopts "a:b:c" opt
do
 case $opt in
  a) AA=$OPTARG ;;
  b) BB=$OPTARG ;;
  c) CC=$OPTARG ;;
 esac
done
shift $(expr $OPTIND - 1)

But now I want to add an option, say d and I don't want it to use any argument, as the code shows below, but it ends with an error, complaining option requires an argument error -- d It seems that getopts can't do that.

while getopts "a:b:c:d" opt
do
 case $opt in
  a) AA=$OPTARG ;;
  b) BB=$OPTARG ;;
  c) CC=$OPTARG ;;
  d) DD="ON" ;;
 esac
done
shift $(expr $OPTIND - 1)

What should I do then? What is the common practice if I want both option types, one can accept argument, while the other doesn't need argument?

like image 806
Daniel Avatar asked Mar 13 '14 15:03

Daniel


1 Answers

The : in the getopts specifier is not a separator. From man getopts:

if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space.

So if you want an option which doesn't take an argument, simply add the character. If you want it to take an argument, add the character followed by :.

like image 166
l0b0 Avatar answered Oct 04 '22 00:10

l0b0