Reputation: 901
I am following IBM's example from their website:
(listing #5) http://www.ibm.com/developerworks/library/l-bash-parameters/index.html
#!/bin/bash
echo "OPTIND starts at $OPTIND"
while getopts ":pq:" optname
do
case "$optname" in
"p")
echo "Option $optname is specified"
;;
"q")
echo "Option $optname has value $OPTARG"
;;
"?")
echo "Unknown option $OPTARG"
;;
":")
echo "No argument value for option $OPTARG"
;;
*)
# Should not occur
echo "Unknown error while processing options"
;;
esac
echo "OPTIND is now $OPTIND"
done
All I want to to is have an option whose name is more than 1 letter. ie -pppp and -qqqq instead of -p and -q.
I have written my program and implementing -help is giving me a problem...
Upvotes: 3
Views: 5608
Reputation: 445
Upfloor's are right. the getopt utility support long options while you can use --option. Maybe you can try this.
#!/bin/bash
args=`getopt -l help :pq: $*`
for i in $args; do
case $i in
-p) echo "-p"
;;
-q) shift;
optarg=$1;
echo "-q $optarg"
;;
--help)
echo "--help"
;;
esac
done
Upvotes: 4
Reputation: 7838
For conventional shell commands, -help
is equivalent to -h -e -l -p
, so if you parse "-help" with getopts
it will treat it as four separate arguments. Because of this you can't have multi-letter arguments prefixed with only a single hyphen unless you want to do all the parsing yourself. By convention, options that aren't just single characters (aka "long options") are preceded by two dashes instead to make things unambiguous.
The convention for help text is to support both -h
and --help
.
Unfortunately bash's getopts
builtin doesn't support long options, but on all common Linux distributions there's a separate getopt
utility that can be used instead that does support long options.
There's more discussion of the topic in this answer
Upvotes: 8