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 ...

+3


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

+8


source


Up. getopt utility supports long options, while you can use --option. Perhaps 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

      

+4


source







All Articles