Register
It is currently Tue Sep 02, 2014 10:37 pm

getopts long name support


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Thu Oct 11, 2012 12:46 pm   

Joined: Tue Sep 27, 2011 12:45 pm
Posts: 8
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.


Top
 Profile  
 PostPosted: Sat Oct 13, 2012 7:48 am   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 535
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.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 7 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP