View Single Post
  #5   (View Single Post)  
Old 9th July 2008
TerryP's Avatar
TerryP TerryP is offline
Arp Constable
 
Join Date: May 2008
Location: USofA
Posts: 1,547
Default

/bin/sh provides a builtin getopts command as a replacement for the getopt program. In FreeBSDs manual page for sh(1) the following information is provided on getopts:

Code:
getopts optstring var
	     The POSIX getopts command.  The getopts command deprecates the
	     older getopt(1) command.  The first argument should be a series
	     of letters, each possibly followed by a colon which indicates
	     that the option takes an argument.  The specified variable is set
	     to the parsed option.  The index of the next argument is placed
	     into the shell variable OPTIND.  If an option takes an argument,
	     it is placed into the shell variable OPTARG.  If an invalid
	     option is encountered, var is set to `?'.	It returns a false
	     value (1) when it encounters the end of the options.
So I assume it is required by one of the POSIX standards defining the behavior of /bin/sh, either way the manual says this implementation was based on SVR4.

OpenBSDs version of the public domain Korn Shell also implements it, the GNU Bourne Again (bash) shell should too.


----


getopts is only useful in your shell scripts if you want to make a script behave like normal unix programs. For example,

wc -l file

prints only the number of lines in 'file', where the wc program usually prints lines, words, and bytes.


The getopt manual page that Carpetsmoker posted explains how to do things like that in a script.

the difference in using the external getopt and the internal getopts command is basically an 's', technical advantages aside.
__________________
My Journal

Thou shalt check the array bounds of all strings (indeed, all arrays), for surely where thou typest ``foo'' someone someday shall type ``supercalifragilisticexpialidocious''.
Reply With Quote