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.

7
  • 2
    getopts support only single char options Commented Oct 18, 2019 at 6:16
  • I need the other option as well! Commented Oct 18, 2019 at 6:21
  • 1
    Don't use getopts then! Or implement parsing options! Commented Oct 18, 2019 at 6:21
  • 1
    Surely you can be creative enough to ensure you don't have two options starting with h in a two option script?? Commented Oct 18, 2019 at 6:27
  • It's not about creativity, it is a specific task which requires this! In addition there are not only two options, i displayed two just for illustration. Commented Oct 18, 2019 at 6:28

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.