proper way to handle corner cases of parsing command line arguments using case command

Viewed 107

I have a bash script which accepts three command line arguments, e.g script is executed like this: script -c <value> -h <value> -w <value>. I would like to ensure that:

  • order of arguments is not important
  • if argument does not have a value, then error message is printed
  • if any of the arguments are missing, then error message is printed
  • if there are unknown arguments, then error message is printed

I accomplished this with following case statements:

#!/bin/bash

while :; do
  case "$1" in
    -h)
      [[ x${2%%-*} != x ]] || { echo "Value for "$1" missing!"; exit 1; }
      host="$2"
      shift 2
    ;;
    -w)
      [[ x${2%%-*} != x ]] || { echo "Value for "$1" missing!"; exit 1; }
      warning="$2"
      shift 2
    ;;
    -c)
      [[ x${2%%-*} != x ]] || { echo "Value for "$1" missing!"; exit 1; }
      critical="$2"
      shift 2
    ;;
    "")
      [[ $host && $warning && $critical ]] || { echo "One of the arguments is missing!"; exit 1; }
      break
    ;;
    *)
      echo "Unknow option"
      exit 1
    ;;
  esac
done

However, maybe case itself has some advanced options which could avoid all those [[ ]] tests? Or maybe I should use another method altogether for processing command line arguments if I want to make sure that corner cases described above are also covered?

1 Answers
Related