Getopt (); getopt_long (); getopt_long_only (); Option

Source: Internet
Author: User
How to analyze the command line parameters sun,-marchday

There are two types of command line options in GNU/Linux: short option and long option. The former uses '-' as the leading character, and the latter uses '--' as the leading character.
. For example, there is a command:

$ myprog -a vv --add -b --file a.txt b.txt - -- -e c.txt

In the GNU/Linux system, a reasonable explanation for this situation is:
A is a short option with a VV parameter;
Add is a long option with no parameters;
B is a short option with no parameters;
Filepath is long, with a TXT file;
B .txt is a parameter;
-It is a parameter, which usually indicates the standard input, stdin;
-- Is an indicator indicating that scanning is stopped. All subsequent parts are parameters, not options;
-E is a parameter;
C.txt is a parameter

To simplify program design, several library functions can analyze command line parameters elegantly. The prototype is as follows:

#include <unistd.h>

int getopt(int argc, char * const argv[],
const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;

#define _GNU_SOURCE
#include <getopt.h>

int getopt_long(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);

int getopt_long_only(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);

Let's take a look at the getopt function used to analyze short parameters. The parameter description is as follows:

Argc and argv are the parameters obtained from the main function and transmitted as is to getopt;
Optstring indicates how to analyze parameters.

There are several notes about optstring:
If the option has a parameter, this option is followed by a colon. For example, in the above example, if optstring is "A: B", it indicates that a has a parameter and B does not have a parameter;
If the option contains an optional parameter, this option is followed by two colons, for example, "A: B", indicating that a may have a parameter or not;
If the optstring starts with ':', it indicates that if the option is specified with a parameter while the actual command line does not have a parameter, getopt returns ':' instead '? '(Return by default '? ', Which is the same as an unrecognized parameter );
If the optstring starts with '+', it indicates that scanning is stopped immediately when an undefined parameter is encountered. The subsequent parts are interpreted as parameters;
If optstring starts with '-', it indicates that if there is no option parameter, it is treated as a parameter of option 1 (not '1 ').

Each time an option is parsed by the function, the option character is returned.

If the option contains parameters, the parameters are saved in the optarg. If the option has optional parameters but no parameters, optarg is null.

If an option is not specified in optstring, the return character '? '. If optstring specifies that an option has a parameter but no parameter, the return character '? 'Or': ', depending on the first character of optstring. The actual values of these two options are saved in optopt.

If the opterr value is 1, an error message is automatically printed (default); otherwise, the message is not printed.

-1 is returned when resolution is complete.

Optind increments every time an argv is parsed. If there is no option parameter, getopt calls this parameter one by default and resolves the next parameter. If no option is available after resolution, optind indicates the index of the first option-free parameter in argv.

The getopt_long () function works in a way similar to getopt (), but it can also receive Long Options. Before receiving the long option, we must define a struct array variable longopts to specify the long option we want to obtain.

struct option {
const char *name;
int has_arg;
int *flag;
int val;
};

Meaning:
Name indicates the name of the long option;
Has_arg indicates whether this option has a parameter. 1 indicates yes, 0 indicates no, and 2 indicates optional;
Flag indicates how long options are returned. If flag is null, getopt_long returns Val. Otherwise, 0 is returned, and flag points to a variable with a value of Val. If the length option is not found, the flag remains unchanged;
Val indicates the value returned, or the variable indicated by flag needs to be loaded.

The last element of the Option array must be filled with 0.

The last parameter longindex of getopt_long points to the subscript of the searched option in the longopts array when the function returns. Longindex can be null, indicating that this value is not required.

Getopt_long_only is similar to getopt_long, But it treats the options starting with '-' As long options. If this option does not match the long option but matches the short option, it can be parsed as a short option.

When the short option is found, getopt_long and getopt_long_only have the same performance as getopt. If the long option is found, if the flag is null, Val is returned; otherwise, 0 is returned. The error is handled in the same way as getopt, but the returned result is '? 'May also be caused by other situations: the options are ambiguous or irrelevant parameters.

Let's take an example from the Linux manual.

#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>

int
main (int argc, char **argv) {
int c;
int digit_optind = 0;

while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
{"verbose", 0, 0, 0},
{"create", 1, 0, ’c’},
{"file", 1, 0, 0},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "abc:d:012",
long_options, &option_index);
if (c == -1)
break;

switch (c) {
case 0:
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);

printf ("/n");
break;


case ’0’:
case ’1’:
case ’2’:
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements./n");
digit_optind = this_option_optind;
printf ("option %c/n", c);
break;
case ’a’:
printf ("option a/n");
break;

case ’b’:
printf ("option b/n");
break;

case ’c’:
printf ("option c with value ‘%s’/n", optarg);
break;

case ’d’:
printf ("option d with value ‘%s’/n", optarg);
break;

case ’?’:
break;

default:
printf ("?? getopt returned character code 0%o ??/n", c);
}
}

if (optind < argc) {
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("/n");
}

exit (0);
}

We use digit_optind and this_option_optind to track whether option 012 is together. For example, the optind of Option-012 and-0-1-2 is different, when the former returns 0, 1, and 2, the optind is the same, while the latter returns the value 1 in turn.

How to parse command line parameters in commentsshell Programming

Use the getopt command to provide the following code snippets for your reference:

#! /Bin/sh

While getopts XYZ: arguments 2>/dev/null
Do
Case $ arguments in
X) echo "option X ";;
Y) echo "option Y ";;
Z) echo "option Z with Arg. $ optarg ";;
/?) Echo "Usage: optdemo [-XY] [-Z argment]"
Exit 1 ;;
Esac
Done

Echo "/$ optind is $ optind/$ opterr is $ opterr"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.