Tuesday, February 26, 2008

Linux: command: how to use getopt

A simple example is here:
http://tldp.org/LDP/abs/html/extmisc.html#EX33A

From
http://www.tomshardware.com/ucg/commands/getopt-15186.html

getopt

UNIX Shell: Shells (ash, bash, bsh, csh, ksh, sh, tcsh, zsh)

Function
Cleans up and checks options given to a shell script. It split option given together and place each option in its own variable. Any additional arguments is placed after --

Syntax
set -- `getopt optstring $*`
getopt optstring parameter
Linux: [ options... ] -- optstring parameter
Linux: getopt [ options... ] -o optstring [ options... ] [ -- ] parame

optstring Specifies a string of option letters that is recognized by the script.


NOTE: If a letter is followed by a colon (:) it will take an argument.

parameter Specifies the options to check. (This is often $*, the argument list to the script).

set -- Sets the argument list $* .

Linux:

-a Allows long options to start with a single -.

-h Shows help information.

-l longoptions Specifies a long option that will be recognized.

-n progname Specifies a program to use to report errors

-o optstring Specifies a list of short options.

-q Disables error reporting

-Q Doesn't generate any output. Errors are reported unless -q is also given.

-s shell Uses quoting conversions of the specified shell (sh, bash, csh or tcsh)

-u Doesn't quote the output.

-T Will test if this is the enhanced version.

-V Shows version information.

File Name: getopt Directory: /usr/bin/ Type: External

Note:
This is very useful to make easy option check in a shell script.

set -- `getopt ab:c $*`
Specifies that a and c don't take an argument but c will.

If argument is: -ac -b hello
It will be converted to: -a -c -b hello --

If argument is: -bhello ucg
It will be converted to: -b hello -- ucg

set -- `getopt -l help ab:c $*`
Also recognizes the long option --help

No comments:

Locations of visitors to this page