title: How to stop getopts from taking blank or null or other options as option value
body: <p>I (presumably everyone) hit by this problem time to time but couldn't find any good workaround by myself. When <code>getopts</code> looks for an argument, it literally takes the next one, even if it's an option. This is what I did to stop that (code snippet):</p>
  
  <pre><code>#!/bin/bash 
  
  function optsGet()
  {
      while getopts ":c:f" opt; do
          case $opt in
              c ) [[ -z "${OPTARG}" || "${OPTARG}" == -* ]] \
                  &amp;&amp; { echo -e "ERROR: Invalid argument\n"; exit 1; }
                  CNAME="${OPTARG}.tEsTsTr"
                  ;;
              f ) FORCE=true
                  ;;
              \?) echo -e "Invalid option: -$OPTARG\n" &gt;&amp;2;;
              : ) echo -e "Missing argument for -$OPTARG\n" &gt;&amp;2; exit 1;;
              * ) echo -e "Unimplemented option: -$OPTARG\n" &gt;&amp;2; exit 1;;
          esac
      done
  
      shift $(($OPTIND - 1))
  }
  
  optsGet "${@}"
  echo -e "CNAME: ${CNAME}\n"
  </code></pre>
  
  <p>but it is still taking blank/null as a valid argument. So, this works:</p>
  
  <pre><code>san@AM0150 testtools$ ./getopts.sh -c -f
  ERROR: Invalid argument
  </code></pre>
  
  <p>But these aren't: </p>
  
  <pre><code>san@AM0150 testtools$ ./getopts.sh -c " " -f
  CNAME:  .tEsTsTr
  
  san@AM0150 testtools$ ./getopts.sh -c \  -f
  CNAME:  .tEsTsTr
  </code></pre>
  
  <p>I was rather expecting <code>Missing argument for -c</code> error. Is there anything I'm missing here? Or does anyone know workaround? Any input will be highly appreciate. Cheers!! </p>
  
  <p><hr>
  <strong>Update (mainly based on <em>devnull</em>'s reply):</strong></p>
  
  <p>Just for the completeness, now I have this little function: </p>
  
  <pre><code>function ifEmpty()
  {
      local VAL=$1
      local OPT=$2
  
      [[ -z "${VAL}" || "${VAL}" =~ ^[[:space:]]*$ || "${VAL}" == -* ]] \
      &amp;&amp; { echo -e "\n  ERROR: Missing argument for option: -${OPT}\n" &gt;&amp;2; exit 1; }
  }
  </code></pre>
  
  <p>then this can be used like this:</p>
  
  <pre><code>c ) ifEmpty "${OPTARG}" "${opt}"
      CNAME=${OPTARG//[[:space:]]}
      ;;
  </code></pre>
  
  <p>for all the options that needs an argument. Cheers!!</p>
  
  <p>PS. for some reason, <code>*[[:space:]]*</code> doesn't work when used in the function.</p>