I (presumably everyone), struck by this problem from time to time, but could not find a suitable workaround. When getopts looks for an argument, it literally takes the next one, even if it is an option. This is what I did to stop this (code snippet):
#!/bin/bash function optsGet() { while getopts ":c:f" opt; do case $opt in c ) [[ -z "${OPTARG}" || "${OPTARG}" == -* ]] \ && { echo -e "ERROR: Invalid argument\n"; exit 1; } CNAME="${OPTARG}.tEsTsTr" ;; f ) FORCE=true ;; \?) echo -e "Invalid option: -$OPTARG\n" >&2;; : ) echo -e "Missing argument for -$OPTARG\n" >&2; exit 1;; * ) echo -e "Unimplemented option: -$OPTARG\n" >&2; exit 1;; esac done shift $(($OPTIND - 1)) } optsGet "${@}" echo -e "CNAME: ${CNAME}\n"
but it still accepts empty / null as a valid argument. So this works:
san@AM0150 testtools$ ./getopts.sh -c -f ERROR: Invalid argument
But this is not so:
san@AM0150 testtools$ ./getopts.sh -c " " -f CNAME: .tEsTsTr san@AM0150 testtools$ ./getopts.sh -c \ -f CNAME: .tEsTsTr
I rather expected the error Missing argument for -c . Is something missing here? Or does anyone know a workaround? Any input will be very valuable. Hooray!!
Update (mainly based on devnull response):Just for completeness, now I have this little function:
function ifEmpty() { local VAL=$1 local OPT=$2 [[ -z "${VAL}" || "${VAL}" =~ ^[[:space:]]*$ || "${VAL}" == -* ]] \ && { echo -e "\n ERROR: Missing argument for option: -${OPT}\n" >&2; exit 1; } }
then it can be used as follows:
c ) ifEmpty "${OPTARG}" "${opt}" CNAME=${OPTARG//[[:space:]]} ;;
for all parameters that require an argument. Hooray!!
PS. for some reason *[[:space:]]* does not work when used in a function.
source share