Article 59H8M bash getopts - help

bash getopts - help

by
GPGAgent
from LinuxQuestions.org on (#59H8M)
I'm going from good - to bad - to hopeless now

I have a nice script working with getopts, I knocked it up from various ddg searches, fine I thought, now I understand how it works.
Or so I thought so I wrote a very simple one and I'm now completely confused, here's the script:Code:#!/bin/bash
SCRIPTNAME=$(basename ${0%.*})

USAGE() { echo -e "$1 - Usage: $(basename $0) [-h help] [-a arg]" 1>&2; }
if (($# == 0))
then
USAGE "No Options Supplied"; exit 1;
fi

USAGE_HELP() {
USAGE "Long Help";
echo " -h - takes no arguments Help - this is it";
echo " -a takes a single argument";
echo " -b takes no argument(s)";
echo " -e takes no argument(s)";
echo " === end of help ======";
}
while getopts ':a:h' OPTION; do
case "$OPTION" in
a) SWITCH_A="-a selected with argument $OPTARG" ;;
h) USAGE_HELP ; exit 1 ;;
?) USAGE "Unknown option -$OPTARG"; exit 1 ;;
:) USAGE "Missing option for $OPTARG"; exit 1;;
*) USAGE "Unimplemented option $OPTION"; exit 1 ;;
esac
done
shift $((OPTIND -1))
echo "SWITCH_A: $SWITCH_A"
echo "Finished Okay";And here it is running with various switches

1 No switch:Code:dev$ ./VerySimpleOpts.sh
No Options Supplied - Usage: VerySimpleOpts.sh [-h help] [-a arg]Thats fine worked as expected

2 -h switch:Code:dev$ ./VerySimpleOpts.sh -h
Long Help - Usage: VerySimpleOpts.sh [-h help] [-a arg]
-h - takes no arguments Help - this is it
-a takes a single argument
-b takes no argument(s)
-e takes no argument(s)
=== end of help ======Good as I expected

3 -a OPT:Code:dev$ ./VerySimpleOpts.sh -a OPT
SWITCH_A: -a selected with argument OPT
Finished OkayThats fine

4 just -a, no argument:Code:dev$ ./VerySimpleOpts.sh -a
Unknown option -a - Usage: VerySimpleOpts.sh [-h help] [-a arg]Nope, I thought it should have gone through the : ) check?

5 -m, an undefined option:Code:dev$ ./VerySimpleOpts.sh -m
Unknown option -m - Usage: VerySimpleOpts.sh [-h help] [-a arg]Nope, I thought it should have gone through the ?) or *) check?

Can someone explain what I'm doing wrongor not comprehending?latest?d=yIl2AUoC8zA latest?i=tiIHlt2Vefg:bQLLTfW5oSU:F7zBnMy latest?i=tiIHlt2Vefg:bQLLTfW5oSU:V_sGLiP latest?d=qj6IDK7rITs latest?i=tiIHlt2Vefg:bQLLTfW5oSU:gIN9vFwtiIHlt2Vefg
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments