Search code examples
bashgetopt

Getopt in shell


I am writing a shell script to parse options. It parses the options correctly but when I omit any input arguments it doesn't come out of the while loop. Can anyone help on this?

TEMP=`getopt -o ha:b:d:e:c: --l ca: \-n "$x" -- "$@"`

eval set -- "$TEMP"

while true; do

  case "$1" in

    -h)      print $USAGE
             exit 0 ;;
    -a)      case "$2" in
               -*|"") error "Option t, requires argument";
                      exit 1;;

               *)  print $2
                   T=${2^^} ; 
                   shift 2 ;;
             esac ;;

    -b)      case "$2" in
               -*|"") error "Option p, requires argument";
                   exit 1 ;;

               *)  print $2
                   PE=${2^^} ; 
                   shift 2 ;
             esac ;;

    -d)      case "$2" in
               -*|"") error "Option f, requires argument";
                      exit 1 ;;

               *)  print $2 ; 
                   IN=$2 ;
                   shift 2 ;;
             esac ;;

    -e)      case "$2" in
               ""|-*) error "Option e, requires argument";
                      exit 1 ;;

               *)  print  $2 ; 
                   KEY=$2 ;
                   shift 2 ;;
             esac ;;
    -c|--ca) case "$2" in
               ""|-*) error "Option c, requires argument"; 
                   exit 1;;

               *)  print $2 ;
                   C=${2};
                   shift 2 ;;
             esac ;;


   --)       shift ;
             break ;;

    *)       error "Invalid Input!" ;
             exit 1 ;;

  esac
done


USAGE:foo.sh -a arg1 -b arg2 -c arg3 -d arg 4 -e arg5

This works fine but

foo.sh -a arg1 -b arg2 -c arg3

doesn't come out of the while loop.


Solution

  • You don't ever exit the loop; how do you expect an exit to happen? A common arrangement is to examine $# at the top, and only proceed if it is zonzero.