BashScripts.org
http://bashscripts.org/forum/

getopts long name support
http://bashscripts.org/forum/viewtopic.php?f=7&t=1653
Page 1 of 1

Author:  jfinn [ Thu Oct 11, 2012 12:46 pm ]
Post subject:  getopts long name support

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=("[email protected]");
    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 [email protected]


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.

Author:  Watael [ Sat Oct 13, 2012 7:48 am ]
Post subject:  Re: getopts long name support

hi,

Code:
getopts_long "@"
with quotes.


`expr' is useful for csh only, other posix shells have arithmetics evaluation.

`sed' can be avoided by using Parameter Expansion (see man bash)

I'd probably simply use positionnal parameters instead of a new array.

if I want to know if an argument begins with '--' I'd use
Code:
[[ $parm =~ ^-- ]]
or even more simply
Code:
[[ $parm == --* ]]


edit:
of course the `eval' part is very dangerous here I could change any --arg(n) to --'rm -rf /' and it'd be evaluated and so executed.

Page 1 of 1 All times are UTC - 6 hours
© 2000, 2002, 2005, 2007 phpBB Group • http://www.phpbb.com