-1

I'm trying to have my getops function run with multiple flags and arguments but instead of short (-f style) flag, I want to accept a long one (--flag style). For example:

if [ $# -lt 1 ]; then
  usage >&2
  exit 1
else
  while $1 "hf:" opt; do
    case $opt in
       h)
          echo "Here is the help menu:"
          usage
          ;;
       f)
          ls -l $OPTARG >&2
          ;;
       \?)
          echo "Invalid option: -$OPTARG" >&2
          ;;
        :)
          echo "Option -$OPTARG requires an argument" >&2
          exit 1
          ;;
    esac
  done
fi

I would like the -h and -f to be --help and --file respectively.

How do I do that?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
John Doe
  • 159
  • 1
  • 10
  • Do you want to know how to use the existing `getopt`/`getopts` commands, or are you trying to write your own version of these? I've answered the former. If it's the latter, show us your code so far, and let us know what specifically you need help with. – John Kugelman May 03 '18 at 14:44
  • Here's a solution, if you still want to use `getopts`: https://stackoverflow.com/a/7680682/8833540 – Kevin Hoerr May 03 '18 at 14:47
  • What is the problem or question? Since Stack Overflow hides the Close reason from you: *"Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](http://stackoverflow.com/help/how-to-ask) page for help clarifying this question."* – jww May 04 '18 at 01:51
  • @jww - I think the question is written in a pretty clear manner . I simply asked how I can have my code support a --flag rather than the - formart. Please do no down vote questions for no logical reason – John Doe May 04 '18 at 07:12
  • 1
    Don't take it personally, his goal in life is do run around editing and downvoting questions -- don't worry, it all comes out in the wash. (did you get `shift` figured out? -- e.g. it just consumes an argument (positional parameter) so that `$2` becomes `$1`, and so on..) – David C. Rankin May 04 '18 at 07:27

1 Answers1

1

getopt will do this for you. It handles short options, long options, options with and without arguments, -- to end option parsing, and more.

Boilerplate usage looks like:

options=$(getopt -o hf: -l help,file: -n "$0" -- "$@") || exit
eval set -- "$options"

while [[ $1 != -- ]]; do
    case $1 in
        -h|--help) echo "help!"; shift 1;;
        -f|--file) echo "file! $2"; shift 2;;
        *) echo "bad option: $1" >&2; exit 1;;
    esac
done
shift

# Process non-option arguments.
for arg; do
    echo "arg! $arg"
done
John Kugelman
  • 349,597
  • 67
  • 533
  • 578