-1

I have a use case in which I have to execute functionality of different methods in shell script. User will call my shell script as I have to read the value of options and on basis of it have to call methods. Please find the sample code below.

./testfile.sh --option1 value1 --option2 value2

#!/bin/bash
#
# Example of how to parse short/long options with 'getopt'
#

OPTS=`getopt --long option1,option2 -n 'parse-options' -- "$@"`

if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi

echo "$OPTS"
eval set -- "$OPTS"

opt=""
id=""

while true; do
echo "Inside while $1 $2"
  case "$1" in
    --option1) echo $1; shift ;;
    --option2 ) echo $2; shift ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

echo "Value for opt  $opt"
echo "Value for id  $id"
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
umesh
  • 312
  • 3
  • 4
  • 15
  • What is your question? – larsks Feb 15 '18 at 13:16
  • I am not able to fetch the options and process the cases. – umesh Feb 15 '18 at 13:32
  • Why do you `echo $2` in the option2 case? If option2 should take an option, then you want `--long option1,option2:` (with a colon). Also you never set a value for either of `opt` or `id` – glenn jackman Feb 15 '18 at 14:39
  • I am totally new to shell script, so I am struggling with this portion. Yes I need the value of both the options. here is the output when I an trying to run the command ./testfile.sh --option1 test --option2 test1 'test' --option2 'test1' -- Inside while test --option2 Yes I didn't set the value for opt and id, because once I will be able to get into case succesfully i will set it there – umesh Feb 15 '18 at 14:56

1 Answers1

0

We can achieve parsing of long option calling using getopt. My USE CASE :- When we only have long option provided then how can we use getopt, because getopt can parse both the short i.e something like '-o, -k. -p etc' and also the long option like "--opt, --pass, etc". When we use getopt, below is the default syntax for it

'getopt -o 'o,p,k' --long opt,pass -n 'parse-options' -- "$@"'

Above line will parse both the long and short option. Solution to my use case is we have pass single quotes for short option, like below, below line will parse only long option i.e opt and pass.

'getopt -o '' --long opt,pass -n 'parse-options' -- "$@"'
umesh
  • 312
  • 3
  • 4
  • 15