I don't actually use getopt or getopts in this function because getopts doesn't support long names and because I didn't really understand the getopt examples I found.
Here's the function:
Code:
getopts_long ()
{
args=("$@");
numargs=${#args[@]};
c=0;
while [ $c -le $numargs ]; do
if [ `echo ${args[$c]} |grep -c ^--` -ne 0 ]; then
nextvar=`expr $c + 1`;
if [ -z ${args[$nextvar]} ]; then
x=`echo ${args[$c]} |sed 's/^--//'`;
eval ${x}="true";
else
if [ `echo ${args[$nextvar]} |grep -c ^--` -eq 0 ]; then
x=`echo ${args[$c]} |sed 's/^--//'`;
eval ${x}=${args[$nextvar]};
x="";
else
x=`echo ${args[$c]} |sed 's/^--//'`;
eval ${x}="true";
fi;
fi;
fi;
c=`expr $c + 1`;
done
}
You can add the following line to the top of your script
Code:
getopts_long $@
For every --variable value you pass the variable will be created and it's value will be the value you passed. If no value is passed the variable will be set to true.
Example:
Code:
./yourscript --arg1 hello --arg2 world --arg3
Within that script you would have $arg1=hello $arg2=world $arg3=true
Enjoy! I've found it to be useful.