1

I have this code, and when I call it in command line, it shows the echo in option/the one I have in each option/ but $OPTARG is undefined. And I have no idea why.

   OPTIND=1
    optm=
    optl=
    while getopts "ml:" opt
    do
    case "$opt" in
    m)
    optm=$OPTARG
    echo "m was triggered"
    ;;
    l)
    moznostl=$OPTARG
echo "l was triggered"
    ;;
   esac
   done
   shift "$((OPTIND-1))"

and my second question is: OPTIND=2 can this be used to start with second argument? I mean it works but wheater it is legit way to do that. for example:

./project first -l second 

so it would skip the first agument and started with -l?

  • 1
    I would usually store the first argument in a variable, then shift. That way I don't tinker around with the value of OPTIND. Furthermore, is there a reason why you do optm=$OPTARG? According to getopts "ml:", the -m flag does not take any parameter. Apart from that, I don't think I understood your question; the slashes are quite confusing: which echo does it show? How do you see that $OPTARG is undefined? – ayekat Mar 19 '15 at 11:55
1

You've got this line

while getopts "ml:" opt

This tells the shell that m may exist but takes no parameter, and that l may appear with exactly one parameter.

I suspect you meant to use getopts 'm:l' opt.

  • Just noticed @ayekat has alluded to the same issue. Kudos there. – roaima Mar 19 '15 at 12:35

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.