Hi Unix Gurus,
i am on learning path of unix, and yet to discover many things. I came across with this requirement where i need to pass parameters but the position of parameters is not fixed so after doing some google search got to know "getopts" can handle that. So here is my code:
function show_help {
echo "Usage: ${0} -b [bankname] -r [region] -w [windowdate]"
echo ""
echo " -b: BankName"
echo " -r: Region"
echo " -w: Windowdate"
exit 0
}
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# set -x
# Get parameters from command line
while getopts "h?b:r:w:f" opt; do
case "$opt" in
b)
BankName=${OPTARG}
;;
r)
Region=${OPTARG}
;;
w)
WindowDate=${OPTARG}
;;
f)
FilePattern=${OPTARG}
;;
h|\?)
show_help
exit 0
;;
esac
done
shift $((OPTIND-1))
[ "$1" = "--" ] && shift
# If required variables aren't setup, show help and exit
unset MISSING_PARAM
if [[ -z ${BankName} ]]; then
MISSING_PARAM="${MISSING_PARAM} b"
fi
if [[ -z ${Region} ]]; then
MISSING_PARAM="${MISSING_PARAM} r"
fi
if [[ -z ${WindowDate} ]]; then
MISSING_PARAM="${MISSING_PARAM} w"
fi
#if [[ -z ${FilePattern} ]]; then
# MISSING_PARAM="${MISSING_PARAM} f"
#fi
if [[ -n ${MISSING_PARAM} ]]; then
echo "Error: Missing required parameter(s)"
for PARAM in ${MISSING_PARAM}; do
echo " -${PARAM}"
done
echo ""
show_help
exit 0
fi
well, now my requirement is i want to pass optional parameter, kindly note i am not talkin about optional arguments that i am aware of if i dont use ":" after any option it will accept optional argument for that option, but what i need is optional parameter.. so if i call my scripts like:
./myscript.sh -b ABC -r PQR -w 20180503 -f 130020003_S-VAN-Sort-CSMxx
it does not show any parameter passed to option "-f" because there is no ":" after -f... what i want is out of 4 parameters 3 are mandatory but last one should be non-mandatory so, both should work i.e
./myscript.sh -b ABC -r PQR -w 20180503 -f 130020003_S-VAN-Sort-CSMxx
and
./myscript.sh -b ABC -r PQR -w 20180503
Is there any way i can handle this in one getopts or do i need to write another case for non-mandatory parameter.
Let me know if require any other info.
TIA