2

I want to use getopts in a Bash script as follows:

while getopts ":hXX:h" opt; do
  case ${opt} in
    hXX ) Usage
      ;;
    h ) echo "You pressed Hey"
      ;;
    \? ) echo "Usage: cmd [-h] [-p]"
      ;;
  esac
done

The idea behind is that I want to have two flags -h or --help for allowing user to be able to use HELP in order to be guided how to use the script and another second flag which starts with h but its like -hxx where x is whatever.

How can I distinguish these two since even when I press --hxx flag it automatically executes help flag. I think the order of presenting them in getopt has nothing to do with this.

Biffen
  • 6,249
  • 6
  • 28
  • 36
asha
  • 83
  • 1
  • 9

1 Answers1

1

The 'external' getopt program (NOT the bash built in getopts) has support for '--longoptions'. It can be used as a pre-procssor to the command line options, making it possible to consume long options with the bash built-in getopt (or to other programs that do not support long options).

See: Using getopts to process long and short command line options for more details.

#! /bin/bash

TEMP=$(getopt -l help -- h "$@")
eval set -- "$TEMP"
while getopts h-: opt ; do
        case "$opt" in
                h) echo "single" ;;
                -) case "$OPTARG" in
                        -help) echo "Double" ;;
                        *) echo "Multi: $OPTARG" ;;
                esac ;;
                *) echo "ERROR: $opt" ;;
        esac
done
dash-o
  • 13,723
  • 1
  • 10
  • 37