1

I'm writing a Bash script to parse command line options and then execute the desired function.

#!/bin/bash

TEMP=`getopt --longoptions help --options h --name 'script.sh' -- "$@"`

if [ $? != 0 ] ; then
  echo "Try 'script.sh --help' for more information." >&2 ;
  exit 1 ;
fi

eval set -- "$TEMP"

while true ; do
  case "$1" in
    -h|--help)
      echo "Usage:";
      exit 0;;
    --)
      shift ;
      break ;;
    *)
      echo "Internal error!" ;
      exit 1 ;;
  esac
done

echo "Remaining arguments:"
for arg do
  echo '--> '"'$arg'" ;
done

./script.sh -- outputs

Remaining arguments:

All of

  • ./script.sh --h
  • ./script.sh --he
  • ./script.sh --hel
  • ./script.sh --help

output

Usage:

and ./script.sh --helps outputs

script.sh: unrecognized option '--helps'
Try 'script.sh --help' for more information.

How do I stop the truncated options from being recognised as the full option? I can't find anything like "end of string" in Bash patterns. Why doesn't -- get detected as the start of --help?

0

From man getopt:

Long options may be abbreviated, as long as the abbreviation is not ambiguous.

So as long as abbreviation is not ambiguous, it will be abbreviated. You could add some other option to make it ambiguous:

TEMP=`getopt --longoptions help helpx --options h --name 'script.sh' -- "$@"`

Will give you something like:

./script.sh    --he
script.sh: option '--he' is ambiguous; possibilities: '--help' '--helpx'
Try 'script.sh --help' for more information.
  • I think I'll just have to live with it. I'm not a Linux person so I don't always know the expected conventions. I don't want to surprise people. – CJ Dennis Sep 19 '19 at 8:44
0

instead of handle options in a more generic way you should care for those options you are interested in

for i in "$@"; do
    case $i in
        -h|--help)
            echo "usage"
            exit 0
            ;;
        --one|--two|--tree)
            continue
            ;;
        *)
            echo "error"
            exit 1
            ;;
    esac
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.