Register
It is currently Wed Apr 23, 2014 12:43 am

getopts problem


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Tue May 04, 2010 9:43 am   
Moderator
User avatar

Joined: Thu Oct 11, 2007 7:12 am
Posts: 224
Location: London - UK
Hi,

I am using getopts to parse various options, however the script always requires an arg that I do not want to force the user to use a switch with.

Code:
while getopts "dfh" options
do
  case "$options" in
    h) usage
       ;;
    f) force=1
       ;;
    d) debug=1
       ;;
  esac
done
mydata=${$OPTIND} # this line (obviously) fails


so I want to be able to call it like so;
Code:
myscript 10.1.1.0


getopts seems to tell me the location where the info I want is in, $OPTIND, but I can't seem to actually use that to get the data. The location is also in $#.

In the above case $OPTIND contains 1 but how do I actually extract the contents of $1 without knowing that it is in position $1 ? the script *may* have been called like so;
Code:
myscript -f 10.1.1.0

in which case I'd need the contents of $2

How do I extract the contents of the last arg without specifying a switch for that arg? The OPTIND line at the end does not work as bash does not do that type of substitution, well not in that way anyway :)

The only way I have thought of atm is to parse $@ using awk to extract the last entry but that seems rather messy and it may be that the supplied arg has spaces etc.

Lastly, being restricted to scripts that will work on RHEL3 the script can only use functions available from bash 2.05b or later.

I hope my babble here is clear enough o_O

Many thanks,
DW


Top
 Profile  
 PostPosted: Tue May 04, 2010 10:15 am   

Joined: Wed Apr 14, 2010 10:23 am
Posts: 17
Code:
shift $((OPTIND-1))
# now do something with $@


See http://wiki.bash-hackers.org/howto/geto ... w_it_works


Top
 Profile WWW  
 PostPosted: Wed May 05, 2010 2:40 am   
Moderator
User avatar

Joined: Thu Oct 11, 2007 7:12 am
Posts: 224
Location: London - UK
perfect, many thanks :x


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

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 4 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:  


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