1

Just started use getopts and found one problem...

For example - have a script with:

while getopts "h:loav" opt; do
case $opt in
h)
  h=$OPTARG
  echo $h
  ;;

But whet I run it:

$ ./ftpclean.sh -h -l
-l

I got second option as argument for first option... So - if user forgot set argument:

$ ./ftpclean.sh -h argument
argument

getopts will set echo *second option*...

Is there any "legal" way to avoid it?

Best solution wich I found - is to add function:

function checkargs () {
if [[ $OPTARG =~ ^-[a/l/o/a/v]$ ]]
  then
  echo "OPTERR"
  exit 1
fi
}

And run it before set variable:

 while getopts "h:loav" opt; do
  case $opt in
h)
  checkargs
  h=$OPTARG
  echo $h
  ;;

So now:

$ ./ftpclean.sh -h -l
OPTERR
1

getopts h: says that the option -h requires an argument. The argument to an option can be either in the same word as the option itself, or if there is nothing there in the next word. The only way to specify an empty argument is to to pass an empty word after the option.

When you write ./ftpclean.sh -h -l, -l is the argument to the option -h. You can also write ./ftpclean.sh -h-l. If you want to pass an empty argument to -h, write ./ftpclean.sh -h '' -l.

It seems that you want to violate the Unix argument convention and require arguments to be in the same word as the command. If you want to do that (which I strongly recommend against, because you'll confuse users and make them curse you for doing something non-standard with no justification), getopts won't help you much, you'd be better off doing your own parsing.

  • No, may be I not exactly put my idea... The problem is, that user can forgot set argument after option -h. In this case - getops will get next option as argument. Question is - how avoid it? – setevoy Nov 18 '13 at 8:27
  • 1
    @setevoy You can't do this. What if the user wants to pass the string -l as an argument to -h? You say you want to reject ./ftpclean.sh -h -l, but you should not: it's valid. I think you don't understand how command line arguments work. There's no intrinsic distinction between options and non-options, options and their arguments they are parsed from left to right. If an argument is -h, it's an option, and the next argument to the command is its argument. – Gilles 'SO- stop being evil' Nov 18 '13 at 10:13
  • Well, so I must add additional check to -h option to be sure that next command is valid argument for -h... Something like function, that I shown in topic start... – setevoy Nov 18 '13 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.