using getopts did not get the input value

96 views Asked by At

I am running the below script, but it looks like the $filename or $srvname did not get the input value. say for eg: ./test.sh -n abcd.net gives the output echo 'Filename or node name must be defined.' it means that, the $srvname did not get the value "abcd.net", please advise am i doing anything wrong. ?

    set -x  

usage () {  

    echo "usage: $0 -n <nodename>"  
    echo "usage: $0 -f <filename>"  
    echo "usage: $0 -h <help>"  
}   



while getopts ":nfh:" opt; do   
   case "$opt" in   
        n)  srvname="$OPTARG" ;;    
        f)  filename="$OPTARG" ;;   
        h)  # help  
            usage   
            exit 0  
            ;;  
        :)  echo "Error: -$OPTARG requires an argument" 
            usage   
            exit 1  
            ;;  
        ?)  echo "Error: unknown option -$OPTARG"   
            usage   
            exit 1  
            ;;  

   esac 
done    


function dosomecheck {  
    echo "do some checks"

}   

if [ "$filename" != "" ] ; then 
  # read file   
  for x in `cat $filename` ; do 
        dosomecheck $x  
  done  
fi  

if [ "$srvname" != "" ] ; then  
  # read file   
  for x in $srvname ; do    
        dosomecheck $x  
  done  
fi  

Thanks in advance

1

There are 1 answers

2
Rakholiya Jenish On BEST ANSWER

Try doing:

while getopts ":n:f:h" opt;

because -n and -f takes argument while -h doesn't.