How can I clean up this options parsing code in a Bash function? It is copy-pasted into a number of functions that need to have a simple "-h" flag for printing usage. I would rather have a generic routine with the logical equivalent of
local prefix_opt1
local prefix_opt2
....
__handle_opts "usage message" "additional getopts flags" "prefix"
For example:
local foo_k
local foo_v
__handle_opts "Usage: ${FUNCNAME[0]}" [-k key -v version] widget\nBuild a widget using the key and version." "k:v:" "foo_"
if [[ -z $foo_k ]] ; then
foo_k="default value"
fi
.....
The functions are to be "sourced" in one's dot-bashrc file.
Here is what the code looks like (note: some of the functions do take options via flags):
function kitten_pet {
local usage="Usage: ${FUNCNAME[0]} [-h] <kitten>\nPet the kitten."
################################################
local help=0
local error=0
local OPTIND
local opt
while getopts ":h" opt "$@"
do
case $opt in
h)
echo -e "$usage"
help=1
break
;;
\?)
echo "Invalid option: -$OPTARG"
error=1
break
;;
esac
done
if [ $error -gt 0 ] || [ $help -gt 0 ] ; then
return 1
fi
shift $((OPTIND-1))
################################################
if [ $# -lt 1 ]
then
echo -e "$usage"
return 1
fi
__kitten_pet "$1"
}
Ordinarily I would use something like node-commander or node-optimist and write the script in JavaScript (or perhaps Python) for scripting needs but I'm trying to make Bash work this time. But Bash is bashing me.