tags:

views:

32

answers:

1

Hi can someone fix this issue, i am not able to get outpt.

I am not able to get output of -p.

#!/bin/bash 

args=`getopt c:m:p $*` 

if [ $? != 0  -o $# == 0 ] 
then 
  echo 'Usage: -c <current-dir> -m <my dir> -p <argument>' 
  exit 1 
fi 

set -- $args 

for i 
do 
 case "$i" in 
         -c) shift;CURRDIR=$1;shift;shift ;; 
         -m) MYDIR=$1;shift;; 
         -p) ARGVAL=$OPTARG;; 
   esac 
done 

echo "CURRDIR = $CURRDIR" 
echo "MYDIR = $MYDIR" 
echo "ARGVAL = $ARGVAL" 

./1.sh -c "def" -m "ref" -p "ref -k ref" 

Expected output

output -c = "def" 
-m ="ref" 
-p ="ref -k ref"
+3  A: 

getopt

args=`getopt c:m:p $*` 

You need to add a colon after the p to indicate that -p takes an argument. Also you should change $* to "$@" for better handling of spaces.

args=`getopt c:m:p: "$@"` 

You are also mixing up getopt and getopts. $OPTARG is a getopts feature. With plain getopt and set you should simply use $2 and then shift off the argument.

-p) ARGVAL=$2; shift 2;; 

At this point you've done as good as you can with getopt. Unfortunately it doesn't handle the multi-word argument to -p no matter what you do. For that, we need to use getopts.

getopts

From getopt and getopts:

Easier to use and generally better than getopt, though of course not available in csh-like shells. You shouldn't be using those anyway.

This works rather differently than "getopt". First, because it's a built-in, you usually won't find a separate man page for it, though "help getopts" may give you what you need.

The old "getopt" is called once, and it modifies the environment as we saw above. The builtin "getopts" is called each time you want to process an argument, and it doesn't change the original arguments .

Using getopts is a lot simpler. Your entire loop can be simplified to this:

while getopts c:m:p: flag
do 
    case "$flag" in 
        c) CURRDIR=$OPTARG;; 
        m) MYDIR=$OPTARG;; 
        p) ARGVAL=$OPTARG;; 
    esac 
done 

No shifting needed, you just read $OPTARG each time to get each option's value.

John Kugelman
+1 nice answer.
glenn jackman