Getopt
Parse command-line arguments from shell scripts
Introduction
Getopt(1) is a program to help shell scripts parse command-line parameters. It is for example included in util-linux (versions upto 2.7.1) for Linux. But, there were some problems with that getopt(1) implementation, as listed in the 'BUGS' section of its man-page:
- Whatever getopt(3) has.
- Arguments containing white space or imbedded shell metacharacters generally will not survive intact; this looks easy to fix but isn't.
- The error message for an invalid option is identified as coming from getopt rather than from the shell procedure containing the invocation of getopt; this again is hard to fix.
- The precise best way to use the set command to set the arguments without disrupting the value(s) of shell options varies from one shell version to another.
Additionally, the example in the manual page does not run correctly (at least not with any bash shell I have tried).
I have written an implementation of getopt(1) to solve some of these problems, while still staying (for all practical purposes) completely compatible with other getopt(1) implementations. It has replaced the old util-linux version, but it should be useful for other Unixes too.
Highlights
- It can do anything that the GNU getopt(3) routines can do.
- It can cope with spaces and shell metacharacters within arguments.
- It can parse long parameters.
- It can shuffle parameters, so you can mix options and other parameters on the command-line.
- It can be easily identified as an enhanced getopt(1) from within shell scripts.
- It can report parse errors as coming from the shell script.
- It compiles cleanly with both libc-5 and glibc-2 (libc6).
Current release
Getopt is included in util-linux. As this package is installed on nearly all Linux distributions, Linux users will have automatic access to it. Others can download it using the link below.
Subversion
A browsable Subversion tree can be found at the ViewVC server.
The Subversion archive can be accessed through the following SVN URI:
svn://svn.frodo.looijaard.name/public/getopt
Documentation
The following documentation is available online:
- The manual page of getopt(1)
- Several example scripts
Explaining how to test whether you are using this enhanced getopt(1) implementation, as well as examples how to call it.