Hi there I am trying to figure out how I would do this:
I need to write a script which takes in user options using Getopts but also as a Case within a Case. I came across this but can't really understand exactly what it is doing, have tried to explain in the # notes - but need someone to tell me if is right.
GETOPTS-CASE-IN A-CASE
Code:
#!/bin/bash
# selection options ":" "-h" "v" "-" + $OPTARGUMENT
optspec=":hv-:"
# while getopts "$optspec set above optchar (case)
while getopts "$optspec" optchar; do
# outer case
case "${optchar}" in
-)
case "${OPTARG}" in
loglevel)
val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
;;
# OPTIND is an index to the next argument to be
# processed, so this next line increases value by 1
# but what is val="${!OPTIND}"; doing?
# is it setting val to be "not OPTIND" so it is then
# written to STDERR?.
loglevel=*)
val=${OPTARG#*=}
opt=${OPTARG%=$val}
echo "Parsing option: '--${opt}', value: '${val}'" >&2
;;
# whats going on here? so argument 1 and argument 2 # are "-" and "loglevel=*" respectively and
# val is now "$OPTARG=" ...why use "#", "*" and "="?
# then echo writes to STDERR
# echo "Parsing option: --
*)
if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
echo "Unknown option --${OPTARG}" >&2
# What is the ":0:1" for? and why not equals to ":"
# what does this mean?
fi
;;
esac;;
v)
echo "Parsing option: '-${optchar}'" >&2
;;
*)
if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
echo "Non-option argument:
'-${OPTARG}'" >&2
# Again what does this mean?
fi
;;
h)
echo "usage: $0 [-v] [--loglevel[=]<value>]" >&2
exit 2
# Why exit 2 here why not 1 for error?
;;
esac
Any help appreciated - new to case and getopts is confusing!!!
Also how can the order be given in any way with getopts? as in - -h -v -* or -v -* -h ?