User specified errors with getopts colon feature

94 views Asked by At

I want the ability to specify whether to use Normal Error Reporting or Silent Error Reporting provided with getopts.

Then I would be able to call my bash function like this

mari -s -n VAL -z VAL

The -s would set Silent Error Reporting (i.e. set opstring=":n:z:"), otherwise Normal Error Reporting (opstring="n:z:") will be used.

Currently I am hardwiring opstring inside the function.

mari() 
{

 impl=""
 if [[ "$impl"  == "SILENT" ]]; then
   opstring=":n:z:"  # Short options string
 else
   opstring="n:z:"
 fi

 while getopts "$opstring" opname; do
  case ${opname} in
    ("n")
      if [ -n "$OPTARG" ]; then
        echo "The string is not empty"
      else
        echo "The string is empty"
      fi
      ;;
    ("z")
      if [ -z "$OPTARG" ]; then
        echo "The string is empty"
      else
        echo "The string is not empty"
      fi
      ;;
    (?)
      ## Invalid Option Found, OPNAME set to '?'
      echo "Invalid option: -$OPTARG" 1>&2
      exit 1
      ;;
    (:)
      ## Required option argument not found, OPNAME set to ':'
      echo "Option -$OPTARG requires an argument" 1>&2
      exit 1
      ;;
  esac
 done
}
1

There are 1 answers

8
KamilCuk On

Modify the opstring once s is encountered.

? is a glob, it matches anything. You have to quote it.

mari() {
    local opstring
    opstring="sn:z:"
    while getopts "$opstring" opname; do
        case ${opname} in
        "s")
            opstring=":${opstring##:}"
            ;;
        "n")
            if [ -n "$OPTARG" ]; then
                echo "The string is not empty"
            else
                echo "The string is empty"
            fi
            ;;
        "z")
            if [ -z "$OPTARG" ]; then
                echo "The string is empty"
            else
                echo "The string is not empty"
            fi
            ;;
        '?')
            ## Invalid Option Found, OPNAME set to '?'
            echo "Invalid option: -$OPTARG" 1>&2
            exit 1
            ;;
        ':')
            ## Required option argument not found, OPNAME set to ':'
            echo "Option -$OPTARG requires an argument" 1>&2
            exit 1
            ;;
        esac
    done
}

echo "no invalid option:"
mari -s -bla
echo "invalid option:"
mari -bla