user1558886
user1558886

Reputation: 15

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.

Upvotes: 1

Views: 398

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753565

While you use getopt instead of the built-in getopts, the loop condition should be:

while [ $# -gt 0 ]
do
    case "$1" in
    ...
    esac
done

You also don't need the variable $TEMP; you could simply use:

eval set -- $(getopt -o ha:b:d:e:c: --l ca: \-n "$x" -- "$@")

Generally, the $(...) notation is preferable to the back-ticks.

Upvotes: 2

tripleee
tripleee

Reputation: 189327

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.

Upvotes: 0

Related Questions