Question

I am writing a script using getopt to parse both long and short parameters. The solution I have so far only accepts one parameter. Is there a way to make this solution accept multiple parameters (eg. both 'THING' and 'COMIC' in the example)?

code:

function usage {
  printf "Usage: %s: [-abh c <URL>] [--ape --bean --comic <URL> --help]" >&2
  exit 2
}

set -- $(getopt -n$0 -u -a --longoptions="ape bean comic: help" "abc:h" "$@") || usage
[ "$#" -eq 0 ] && usage

while [ "$#" -gt 0 ];do
case "$1" in
  # Long options
  --ape)   THING='ape';shift;;
  --bean)  THING='bean';shift;;
  --comic) COMIC='yes';COMIC_URL="$2";shift;;
  --help)  usage;break;;
  -a)      THING='ape';shift;;
  -b)      THING='bean';shift;;
  -c)      COMIC='yes';COMIC_URL="$2";shift;;
  -h)      usage;break;;
  --)      shift;break;;
  -*)      usage;;
  *)       break;;
esac
shift
done

if [ ! -z $THING ]; then
  echo "THING:$THING"
fi

if [ $COMIC == 'yes' ]; then
  $BROWSER $COMIC_URL || echo "Sorry, could not find your comic!"
fi
Was it helpful?

Solution

There could be other problems, but what I see immediately is that you write:

--ape)   THING='ape';shift;;

(and similarly for other cases) and then do:

shift

after the case is done. This means that in the case of --ape and many other cases, you are shifting twice.

Simply remove the shift inside the cases and do a shift once and for every case after esac.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top