Linux command-line options and parameters

Source: Internet
Author: User

1. Main function Parameter form

int Main (int.Char char *env[]); // the first parameter, ARGC, represents the number of arguments on a command line // The second parameter points to each parameter in turn, such as "Ls-l", argv[0] to "LS", argv[1] to "-L", argv[2] to null // The third parameter is a list of current process environment variables

2, command line parameter identification

When you enter a command at the command line, the position of the option is arbitrary, such as ls-l-A and Ls-a-L are the same effect

2.1, getopt (int argc, char *argv[], char *optstring) introduces header file "Unistd.h"

The first parameter, the second argument, and the first two arguments of the main function, and the third parameter, optstring, defines the form of options and parameters

(1) A single character indicates that the option has no parameters

(2) A single colon followed by a single character, indicating that the option must have parameters followed by a space separating the options and parameters

(3) A single character followed by a double colon, indicating that the option can have parameters or no parameters, if there are parameters, the parameters must be immediately after the option

Such as:

AB:C::

Option A has no parameters, option B has a parameter and is separated by a space; Option C can have parameters or no parameters, and if there are arguments, the arguments must follow the options

In addition, there are 4 global variables related to getopt

int optopt: Store options that do not meet optstring requirements

Char *optarg: Parameter pointer to the current option

int Optind: After determining the options and corresponding parameters, point to the next argv parameter

int Opterr: If set to 0, getopt do not want to stderr output error message

Invocation principle:

Each time the getopt is called, the corresponding option is returned so that Optarg points to the parameter corresponding to the option. If the option does not satisfy the optstring rule, then return '? ' and save this option to optopt, or 1 if parsing is complete.

After parsing, getopt rearranges the parameters in the argv, and all non-conforming options and parameters are placed at the end of the argv (where the options are before, the parameters are behind), and the Optind points to the starting subscript of these non-conforming option parameters in argv.

  1#include <stdio.h>2#include <unistd.h>3   4 intMainintARGC,Char* * argv,Char**env) {  5     intRes; 6Opterr=0; Do not display error messages7      while(res = getopt (argc, argv,"ab:c::")) != -1){  8         Switch(res) {9              Case 'a': Tenprintf"option=a\toptarg=%s\toptopt=%c\toptind=%d\targv[optind]->%s\n", Optarg,optopt,optind,argv[optind]);  One                  Break;  A              Case 'b':  -printf"option=b\toptarg=%s\toptopt=%c\toptind=%d\targv[optind]->%s\n", Optarg,optopt,optind,argv[optind]);  -                  Break;  the              Case 'C':  -printf"option=c\toptarg=%s\toptopt=%c\toptind=%d\targv[optind]->%s\n", Optarg,optopt,optind,argv[optind]);  -                  Break;  -              Case '?':  +printf"option=?\toptarg=%s\toptopt=%c\toptind=%d\targv[optind]->%s\n", Optarg,optopt,optind,argv[optind]);  -                  Break;  +         }  A   at     }  -printf"over\noptarg=%s\toptopt=%c\toptind=%d\targv[optind]->%s\n", Optarg,optopt,optind,argv[optind]); Print three global variable final values -     inti =1 ;  -printf"******************************************\n");  -      for(; i < argc; i++{//Print reorder command-line arguments -printf"%s\n", Argv[i]);  in     }  -}

sudo./main-a-B bbb-c ccc-d DDD
Option=a optarg= (null) optopt= optind=2 argv[optind]->-b
Option=b optarg=bbb optopt= optind=4 argv[optind]->-c
Option=c optarg= (null) optopt= optind=5 ARGV[OPTIND]->CCC
Option=? optarg= (NULL) Optopt=d optind=7 ARGV[OPTIND]->DDD
Over
optarg= (NULL) Optopt=d optind=6 ARGV[OPTIND]->CCC
******************************************
-A
-B
Bbb
-C
-D
Ccc
Ddd

2.2, Getopt_long

Not only does it recognize short options (command-short options), but it also supports long options (command-long option).

int Getopt_long (int argc, char **argv, char * shortopt, struct option * longopt, int *index) Note: The struct option introduces the header file "G Etopt.h "

The first three parameters are the same as the getopt parameters, and the shortopt defines the short options and the form of the parameters.

The fourth parameter defines a struct-option array,

The fifth parameter records the long option in the subscript of the longopt array, which is normally set to null

struct option{
const char *name; Long option Name
int has_arg; 0 means that the option has no parameters, 1 means that there must be parameters, and the 2 parameter is optional
int *flag; Normally null, the Getopt_long returns Val; otherwise, the value of Val is assigned to the shaping variable pointed to by flag, and the function returns a value of 0
int Val; Usually set to the short option corresponding to the long option, if flag is null, Val is the return value of the function. Otherwise assign Val to the variable that flag points to
};

If you do not want to support the short option, let Shortopt be an empty string, but it cannot be set to NULL.

  1#include <stdio.h>2#include <unistd.h>3#include <getopt.h>4 intMainintARGC,Char**ARGV,Char**env) {  5     intres;//Save function return value6     structOption longoption[4]={//define long option array7{" Help",0Null'h'},  8{"version",0Null'v'},  9{"Output",1Null'o'}, Ten{NULL,0Null0}  One     };  AOpterr=0;//Do not output error messages -     intindex; The long option is located in the subscript of the longoption -      while( -1! = (res = Getopt_long (argc, argv,"HVO:", Longoption,&index))) {  the         Switch(res) { -              Case 'h':  -printf"option=help\n");  -                  Break;  +              Case 'v':  -printf"option=version\n");  +                  Break;  A              Case 'o':  atprintf"option=output,output path=%s\n", Optarg);  -                  Break;  -              Case '?':  -printf"error\n");  -                  Break;  -         }  inprintf"index in longoption is%d\n", index);  -     }  to   +     return 0;  -}

Output:

sudo./main-h
Option=help
Index in Longoption is-1218614280//For short options, the function's fifth argument is invalid

sudo./main-o/home/out
Option=output,output Path=/home/out
Index in Longoption is-1219220488

sudo./main--version
Option=version
Index in Longoption is 1

sudo./main--output/home/out
Option=output,output Path=/home/out
Index in Longoption is 2

Linux command-line options and parameters

Related Article

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.