Bash getopts command

I am following IBM's example from their website:

(Listing # 5)

echo "OPTIND starts at $OPTIND"
while getopts ":pq:" optname
    case "$optname" in
        echo "Option $optname is specified"
        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"
    echo "OPTIND is now $OPTIND"


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

2 answers

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.

The topic is further discussed in this answer



Up. getopt utility supports long options, while you can use --option. Perhaps you can try this.

args=`getopt -l help :pq: $*`
for i in $args; do
    case $i in
    -p) echo "-p"
    -q) shift;
        echo "-q $optarg"
        echo "--help"




All Articles