Bash getopts command
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 is an option whose name is more than 1 letter. those. -pppp and -qqqq instead of -p and -q.
I wrote my program and executed -help which gave me the problem ...
source to share
For normal shell commands, it's -help
equivalent -h -e -l -p
, so if you parse "-help" with it getopts
, it treats it as four separate arguments. Because of this, you cannot have multi-letter arguments prefixed with only one hyphen unless you want to do all the parsing yourself. By convention, parameters that are not just single characters (aka "long parameters") are preceded by two dashes instead of making things unambiguous.
Help text for context should support both -h
, and --help
.
Unfortunately, the bash getopts
builtin does not support long options, but all common Linux distributions have a separate utility getopt
that can be used instead that does support long options.
source to share