getopts is used by shell procedures to parse positional parameters.
Only single letter option. d is valid but not de
script.sh -p valuep -d valued -f
while getopts "p:d:" option
do
case "$option" in
p) VARIABLE_FOR_P="${OPTARG}";;
d) VARIABLE_FOR_D="${OPTARG}";;
?) echo -e "Usage";;
*) echo -e "option ${OPTARG} unknown. Usage:\n" ; exit 1 ;;
esac
done
where:
if [[ -z "$VARIABLE_FOR_P" ]]; then
echo "VARIABLE_FOR_P:"
read VARIABLE_FOR_P
# Test if null
[[ "${VARIABLE_FOR_P:?The parameter is null sorry}" ]]
fi
getopts optstring name [args]
where:
Each time it is invoked, getopts set the following variable:
At the end of the process, OPTIND is set to the index of the first non-option argument, and name is set to ?.
When the end of options is encountered, getopts exits with a return value greater than zero.
getopts returns:
If the first character of optstring is a colon, silent error reporting is used.
If the variable OPTERR is set to:
If a required argument is not found:
If a required argument is not found:
If an invalid option is seen:
The option character found is placed in OPTARG and no diagnostic message is printed.