LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Using getopts in Shell properly?? (http://www.linuxquestions.org/questions/programming-9/using-getopts-in-shell-properly-923357/)

khandu 01-11-2012 09:49 PM

Using getopts in Shell properly??
 
I have a program which is basically written in sh (has to be) and it is trying to read inputs from the command line and if no input is given then it takes the default value.

Here is the code

Code:

#!/bin/sh

if [ -f /.default ]
then
. /.default
fi

#Set Default Values from the file
DN=$DEFAULTDN
PD=$DEFAULTPD
RPD=$DEFAULTRPD
HOSTNAME=`hostname`

while getopts D:w:r:h:p:i:t: name
do
  case $name in
    t)  TYPE=$OPTARG;;
    D)  DN=$OPTARG;;
    w)  PD=$OPTARG;;
    r)  RPD=$OPTARG;;
    h)  HOSTNAME=$OPTARG;;
    p)  if [ $TYPE = option1 ]
        then
        NUM=747
        elif [ $TYPE = option2 ]
        then
        NUM=777
        fi
        ;;
    i)  if [ $TYPE = option1 ] ; then
                IPATH='/net/install/$HOSTNAME'
        elif [ $TYPE = option2 ] ; then
                IPATH='/net/install2/$HOSTNAME-opt2'
        fi
        ;;

    ?)  usage
        exit 1
        ;;
  esac
done

echo $TYPE
echo $DN
echo $PDN
echo $HOSTNAME
echo $NUM
echo $IPATH

Basically if the file is called test.sh I want the user to run it with mininum commands

Code:

./test -t (option1|option2)
Once he specifies that, and if all the other are not specified (i.e. D w r h etc) then it will take the default.. If even -D -w -r etc are mentioned then it overrides the default value

This script is not working. It is sourcing correctly from the file and assigning the default value and echo out is correct. But I think because I am not mentioning -D -w -r etc , the getopts does not work

Can anyone suggest how to get this working??

Ta

grail 01-12-2012 01:15 AM

You will have to define further, "does not work"? Seems to provide the output I would expect based on script and input.

Reuti 01-12-2012 07:15 AM

If I get it right, the options p and i shouldn’t get a colon behind them as you don’t use $OPTARG in these cases. If an option like -p isn’t specified, its case won’t get executed. Do you referring to a missing set $NUM and $IPATH? Maybe these two should just go behind the case statement as they should always be executed.


All times are GMT -5. The time now is 08:09 AM.