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..
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