i have the following scenario want to run the following script with manadory and optional arguments inside a bash script

Manadory options are :

filename=""
port=""
optional arguments

type -t [A/B]
balances -b bal
prices -p

./test filename port -t A -b bal

my code i have that won't parse the options is
This is what i have

!/bin/bash

filename=""
port=""

while getopts b:t:p opt
 do
      case $opt in
          b) BAL="${OPTARG}"
             if [ "$BAL" == "" ]
             then
                print_usage $0
             else
                echo "Balances is " $BAL
             fi ;;

          t) TYPE="$OPTARG";;
          p) PRICES="$OPTARG";;
          ?) print_usage $0
             exit 1;;
      esac
done
echo "Balances:                "$BAL
echo "Type:                    "$TYPE

Any ideas

Recommended Answers

All 5 Replies

Please use the (CODE) button
Please tell us specifically what "won't parse the options" means. Do you get options that are incorrect? Does the script run, but no options are seen? What?

Please use the (CODE) button
Please tell us specifically what "won't parse the options" means. Do you get options that are incorrect? Does the script run, but no options are seen? What?

Ok sorry I want to be able to pass in the manadory options and then the optional

the Manadory options are been parsed but -t -p -b aren't been parsed just ignored .

this is what i want
test filename port -t -p 123 -b we
so far filename and port but -t -p -b are not been parsed

Any ideas ?!?
have but the

while getopts t:p:b: opt ; do
...

done
filename="$1"
port="$2"

shift $(( OPTIND-2 ))

My version of getopts wants only flagged options, so try this:

filename=$1
port=$2
shift 2
while getopts t:p:b: opt ; do
 # ...
done

Of course that doesn't have any error checking etc

the above exmaple gets the mandatory options missed up with the optional arguments .

filename=$1
  
      port=$2
 
      ext= $3

      shift 3
   
      while getopts t:p:b: opt ; do
   
  case $opt in
               t) tfile="${OPTARG}";;
               p) tdir="${OPTARG}";;
               b) tbl="${OPTARG}";;
               ?) print_usage $0
            exit 1;;
   esac

   
      done
echo "file = $file"
echo " Port =$port "
echo " Ext= $ext
echo  "opt1 = $tfile "
echo " opt2 = $tdir"
echo " opt3 = $tbal"

if i run this script with wrong numbe of mandatory arguments and use optional argumnets it will assign the optional to the mandatory argumnets .
./bscript file1 -t BLAH

result
file = file1
port = -t
ext = BLAH

how can i avoid this from happening ??

Call the script with the options before the arguments, and parse the options first.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.