Hi,
i need to implement a command that looks like other linux/unix commands with proper parameter validation.I saw the usage of getopt but i dont know how to use it to support both short and long options in my script.
for example , commandname -f filename -db database
commandname --help
i need to do validation for the above options to my command.Please help me in using getopt to achieve the same.
Thanks ,
Padmini
It will go something like this :
while getopts "f:d:h" flag
do
# echo $flag $OPTIND $OPTARG
case $flag in
f) echo $flag "FILE="$OPTARG
;;
d) echo $flag "Database="$OPTARG
;;
h) echo Help
;;
*) echo Usage
;;
esac
done
to use -db and --help you can achieve using $@ with while loop and case statement. I dont know whether it is possible using getopt(s)
Hi,
I am new to shell scripting.what it means using while with $@?what is the significance of $@?
$@ is the argument passed.
e.g.
cmd -a file -d database
$@ will contain "a file -d database"
Use getopt option as specified below in code..
#!/bin/bash
args=`getopt abc: $*`
if test $? != 0
then
echo 'Usage: -a option_a -b option_b -c option_c'
exit 1
fi
set -- $args
for i
do
case "$i" in
-a) shift;shift; opt_a=$1;echo "flag a is set to $opt_a";;
-b) shift;opt_b=$2;echo "flag b is set to $opt_b";;
-c) shift;opt_c=$3;echo "flag c is set to $opt_c";;
esac
done
Now you can use $opt_a, $opt_b, $opt_c as value for variables...
how can i use long options with -l option in getopt.Please give me an example.
Thanks for the replies.Using getopts am facing a problem.for ex, if i have a command
listcert -t -k keystore -p password -l label.My optstring is tp:k:l: OPTIONS since t doesnt have any argument.
if i give the command like this listcert -t -k -p passw0rd
getopts takes -p as a argument to -k .But here i failed to give an argument to -k.It doesnt show any error for this.How can i tackle this problem?Please help me