0

I am using getopts to process the input arguments. I have problem in reading optional argument value.
When I invoke the script with arguments test.sh -t test -r server -p password -v 1
$OPTARG is not returning the value of the optional argument -v.

Can anyone let me know how to process the optional argument value?

#!/bin/bash

usage() 
{
cat << EOF
usage: $0 options

OPTIONS:
   -h      Show this message
   -t      Test type
   -r      Server address
   -p      Server root password
   -v      Verbose
EOF
}

TEST=
SERVER=
PASSWD=
VERBOSE=

echo "======111======"
while getopts "ht:r:p:v" OPTION
do
     case $OPTION in
         h)
             usage
             echo "===Option h selected=="
             exit 1
             ;;
         t)
             TEST=$OPTARG
             echo "====option t selected===$TEST"
             ;;
         r)
             SERVER=$OPTARG
             echo "=====option r selected==="
             ;;
         p)
             PASSWD=$OPTARG
             echo "====option p selected==="
             ;;
         v)
             VERBOSE=$OPTARG
             echo "======option v selected===$VERBOSE"
             ;;
         ?)
             echo "====unknown option selected===="
             usage
             exit
             ;;
     esac
done

echo "========222===="
savanto
  • 4,470
  • 23
  • 40
Tech Tech
  • 141
  • 2
  • 10
  • 3
    I believe you are missing a colon `:` after the `v` in the `getopts` call. It should be `while getopts "ht:r:p:v:"`. – savanto May 29 '14 at 23:09
  • Alternatively you could just write something like `((VERBOSE++))` and avoid an argument altogether – jaap May 29 '14 at 23:36

1 Answers1

0
  1. Do the thing in the case statement.

    case $OPTION in
      v)
        VERBOSE=$OPTARG
        do_the_thing $OPTARG
        ;;
    esac
    
  2. Do the thing after the case statement.

    if [ ! -z "$VERBOSE" ]; then
      do_the_thing "$VERBOSE"
    else
      do_not_do_the_thing
    fi
    
Sammitch
  • 30,782
  • 7
  • 50
  • 77