LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   getopts (https://www.linuxquestions.org/questions/programming-9/getopts-754234/)

kj6loh 09-10-2009 02:32 PM

getopts
 
How do you read multiple arguments with getopts? The following is a test case:

$ cat test.sh
#!/bin/bash
ECHO=/bin/echo
while getopts "hmq?" opt; do
case "$opt" in
"m") MYWAY=1;
$ECHO "MYWAY"
shift;
;;
"q") QUIET=1;
$ECHO "QUIET"
shift;
;;
"h" | "?")
$ECHO "Usage: $0 [-m| -q]"
exit 0
;;
esac
done
shift $(($OPTIND - 1))
$ ./test.sh -m
MYWAY
$ ./test.sh -q
QUIET
$ ./test.sh -q -m <-- Shouldn't it read -m too?
QUIET
$ ./test.sh -t <-- Why is this caught
./test.sh: illegal option -- t
Usage: ./test.sh [-m| -q]
$ ./test.sh - <-- And not this?
$

acid_kewpie 09-10-2009 02:40 PM

I was getting a fair bit confused with getopt and getopts earlier in the week, I found this article really useful - http://aplawrence.com/Unix/getopts.html and ended up migrating from getopt to getopts with the help of the really simple example he gives.

For your specific questions, firstly I think as your shifting AND using the options as a while input you're jumping over it. secondly there's nothing wrong with no options by default, it's merely an empty set of data to work on.

catkin 09-10-2009 02:45 PM

You don't need the "shift"s in the getopts loop; getopts does it all for you.

When posting code, it's easier to read if you put it in code tags.

kj6loh 09-10-2009 03:50 PM

Quote:

Originally Posted by acid_kewpie (Post 3677749)
I was getting a fair bit confused with getopt and getopts earlier in the week, I found this article really useful - http://aplawrence.com/Unix/getopts.html and ended up migrating from getopt to getopts with the help of the really simple example he gives.

For your specific questions, firstly I think as your shifting AND using the options as a while input you're jumping over it. secondly there's nothing wrong with no options by default, it's merely an empty set of data to work on.

Yep, thanks I shifted from a case to getopts as I now have more than a few
switches.

kj6loh 09-10-2009 03:53 PM

Quote:

Originally Posted by catkin (Post 3677759)
You don't need the "shift"s in the getopts loop; getopts does it all for you.

When posting code, it's easier to read if you put it in code tags.

I was wondering where my formatting went!


All times are GMT -5. The time now is 04:10 PM.