boilerplate code for Linux getopt

Linux getopt command is often used to parse script options. I find a piece of boilerplate code for this command and mark it in this post for further reference.

  options=$(getopt --name "demo.sh" -o "f:l:ds" -l "file:,list:,debug,save" -- "$@")

  if [ "$?" -ne 0 ]; then
    exit 1
  fi

  eval set -- "${options}"

  while true; do

    case "$1" in
    -f | --file )
      shift
      file=$1
      ;;
    -l | --list )
      shift
      list=$1
      ;;
    -d | --debug )
      debug=1
      ;;
    -s | --save )
      save_image
      ;;
    --)
      shift
      break
      ;;
    esac

    shift
  done

-o is used to specify the short options, while -l is used to specify the long options. A colon following the option name indicates that the option requires a option argument.