Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add usage content in shell script without getopts

I have script where i need to display usage command in case user miss any mandatory information while executing script.

Usage : Script -s <server> -i <instance> -u <user> -p <password> <query> -w <warning value> -c <critical value>

With explanation about all the OPTIONS

I'm getting values from arguments as below variables fashion. But I want this usage with validations in shell script.

SERVER=$1
INSTANCE=$2
USER=$3
DB_PASSWD=$4
QUERY=$5
VAL_WARN=$6
VAL_CRIT=$7

I have tried using getopts, But failed to use since <query> doesn't have a -q parameter before passing the value.

I have tried finding all other ways, But everyone suggested getopts which is not feasible solution for me.

Please help me on this..

like image 445
San Avatar asked Feb 20 '13 08:02

San


2 Answers

Use shift to iterate through all of your arguments, something like:

#!/bin/sh

usage ()
{
  echo 'Usage : Script -s <server> -i <instance> -u <user> -p <password>'
  echo '                  <query> -w <warning value> -c <critical value>'
  exit
}

if [ "$#" -ne 13 ]
then
  usage
fi

while [ "$1" != "" ]; do
case $1 in
        -s )           shift
                       SERVER=$1
                       ;;
        -i )           shift
                       INSTANCE=$1
                       ;;
        -u )           shift
                       USER=$1
                       ;;
        -p )           shift
                       PASSWORD=$1
                       ;;
        -w )           shift
                       WARNINGVAL=$1
                       ;;
        -c )           shift
                       CRITICVAL=$1
                       ;;
        * )            QUERY=$1
    esac
    shift
done

# extra validation suggested by @technosaurus
if [ "$SERVER" = "" ]
then
    usage
fi
if [ "$INSTANCE" = "" ]
then
    usage
fi
if [ "$USER" = "" ]
then
    usage
fi
if [ "$PASSWORD" = "" ]
then
    usage
fi
if [ "$QUERY" = "" ]
then
    usage
fi
if [ "$WARNINGVAL" = "" ]
then
    usage
fi
if [ "$CRITICVAL" = "" ]
then
    usage
fi

echo "ALL IS WELL. SERVER=$SERVER,INSTANCE=$INSTANCE,USER=$USER,PASSWORD=$PASSWORD,QUERY=$QUERY,WARNING=$WARNINGVAL,CRITIC=$CRITICVAL"

Should do the trick.

EDIT: added argument validation in the script as suggested by @technosaurus

like image 177
matt.nguyen Avatar answered Oct 03 '22 00:10

matt.nguyen


getopts is bitching for a good reason. you should change your script's interface to conform to what people expect.

alternatively, you could use getopts twice, first for the pre-query options, shift, then for the rest.

like image 38
just somebody Avatar answered Oct 02 '22 22:10

just somebody