How to compile a complete Linux Command

Source: Internet
Author: User

Author: gzshun. Original Works. Reprinted, please indicate the source!
Source: http://blog.csdn.net/gzshun

A complete Linux Command requires the following important components:
1. Usage
2. Command Line Parameters
3. Portability

1. Usage

In each command, a usage function is required. Of course, this function is not required for the name. After reading a lot of open-source software, almost all of them use usage names. Generally, usage is called only when users enter irregular command line parameters, that is, the detailed usage is printed. For example, if I input an unsupplied parameter to a Linux Command, the execution result is as follows:

gzshun@ubuntu:~/c/getopt$ e2fsck -xe2fsck: invalid option -- 'x'Usage: e2fsck [-panyrcdfvtDFV] [-b superblock] [-B blocksize]                [-I inode_buffer_blocks] [-P process_inode_size]                [-l|-L bad_blocks_file] [-C fd] [-j external_journal]                [-E extended-options] deviceEmergency help: -p                   Automatic repair (no questions) -n                   Make no changes to the filesystem -y                   Assume "yes" to all questions -c                   Check for bad blocks and add them to the badblock list -f                   Force checking even if filesystem is marked clean -v                   Be verbose -b superblock        Use alternative superblock -B blocksize         Force blocksize when looking for superblock -j external_journal  Set location of the external journal -l bad_blocks_file   Add to badblocks list -L bad_blocks_file   Set badblocks list

Each command line option represents a function. Some options can be followed by parameters, such as [-B superblock] [-B blocksize] In e2fsck.

2. Command Line Parameters
At, the usage printing information has been pasted. The-P,-N and so on above are the command line parameters. This article also focuses on the use of this command line parameter. When executing a Linux Command, you may only need to add one option (for example, CP-...), you may also need to follow an option (for example, e2fsck-C0 or e2fsck-C 0). In fact, "e2fsck-C0" is equivalent to "e2fsck-C 0. Here we analyze the merits of the command line parameters thanks to the "getopt" function. getopt () is used to analyze the Parameter options. For details, refer to: (Network Printer communication in Chapter 21st of advanced programming in UNIX environment)
P619), of course, in the book "Advanced Programming in UNIX environment", this function is just a little bit of it, not detailed.

3. Portability
Usually, the portability of an open-source software is considered quite well. Open-source software on the Linux platform is often transplanted to different platforms, which must take into account the portability of different platforms. Of course, I lack the knowledge of software portability and need to be improved. This article does not explain portability.

1. Why should I write a complete Linux Command?
On the Linux platform, many important functions are implemented through the command line. Maybe we also need to implement our own program by ourselves at ordinary times. Of course, we need a relatively quality one. The design of a Linux Command is involved here. The first step is to analyze the command line parameter options.
Write a complete Linux Command by yourself. The title here is a bit blown. I was going to write a relatively complete CP command, but considering the process, there are a lot of things to deal, including the attributes of files and directories, as well as recursion, removing the working hours, I don't want to write it if I have limited evening time, which is also a relatively easy problem. The CP command is no longer familiar to Linux users. Many programmers write CP commands on the Internet, but I don't think it is complete, some CP programs on the Internet directly read the source file and write it to the target file. They only write a while loop, so there is no complete Linux Command. We usually use the CP command. The source code contains 1063 lines, including comments. A simple function actually involves many features on the Linux platform. We need to consider the file attributes, directory attributes, and permissions, user and group ID, modification time, and State modification time.

Ii. Examples of Linux commands?
For example:
Copy an src directory to the DST directory. There may be three methods:
1. CP-a SRC DST
2. CP Src-A DST
3. cp src dst-
All these three commands can copy the src directory to the DST directory. Here is the benefit of the command line parameter, which is the benefit of the getopt function. If you write a command without using the getopt function to process the command line parameters, you cannot write these three command line parameters.

Example:
E2fsck, a disk detection tool. This function has an option [-c fd], followed by a parameter. This option is to select a different progress to print messages. There are also several ways to write:
1. e2fsck/dev/sda1-C0
2. e2fsck/dev/sda1-C 0
Command line parameters also support this form. The options can be written together with the parameters followed by the options or separated, but must be followed by the options.

Of course, this article cannot write complete Linux commands, the level is limited, just write the parsing part of the command line parameters.

Example: A simple test program is used to print program parameters;
./Cp aa bb cc dd ee-l-d

// Print out the argv two-digit array of the main function.
Argv [0] =./CP
Argv [1] = AA
Argv [2] = bb
Argv [3] = cc
Argv [4] = dd
Argv [5] = EE
Argv [6] =-l
Argv [7] =-d
// Here is the result of argv changes after getopt is called.
Argv [0] =./CP
Argv [1] =-l
Argv [2] =-d
Argv [3] = AA
Argv [4] = bb
Argv [5] = cc
Argv [6] = dd
Argv [7] = EE

In this example, the following results are obtained:
1. The getopt function has the sorting function;
2. argv is a modifiable two-dimensional array;

3. How to Use getopt?
1. Sorting
Getopt sorts the command line parameters first. The options are in front, the remaining parameters are in the back, and The 0th parameters are always the program itself;
Sorting rules:
Only the parameters with the "-" option and this option are mentioned after the program, and the rest are placed at the end. However, the original Parameter order is not changed, so it is a bit difficult to understand, let's look at the example:
CP-a-r src1/src2/src3/DST/
The task of this command is to copy the src1, src2, and src3 directories to the DST directory. The src1, src2, and src3 parameters must be in front of the DST parameter, so getopt will not disrupt the original Parameter order, example:
CP src1/src2/-A src3/-r DST/
After getopt processing, the argv array is changed to CP-a-r src1/src2/src3/DST/, and the original sequence of-a and-R remains unchanged, -R is behind.

2. Parameter Parsing
Some Command Options are followed by a parameter, which can be numbers, letters, or strings. Example:
E2fsck/dev/sda1-C0. Here, the-C option parameter is 0. You can also write e2fsck/dev/sda1-C 0, which is equivalent to the preceding command.

3. Usage of getopt
Finally, it's time to get to getopt.
The getopt function declaration in the unistd. h header file contains the following functions and global variables:

#include <unistd.h>extern char *optarg;extern int optind;extern int opterr;extern int optopt;extern int getopt(int argc, char * const argv[], const char *optstring);

Here is an example (virtual): mycp-a-B hello-c123 SRC DST
Char * optarg:-B's optarg is hello,-C's optarg is 123, and optarg is the parameter followed by the option;
Int optind: The subscript of the next parameter to be processed (argv );
Int opterr: If opterr is set to 0, getopt does not output the error message. Otherwise, an error is returned, for example (e2fsck: Invalid option -- 'X ')
Int optopt: When the command line option character is not included in optstring or the option lacks necessary parameters, this option is stored in optopt
Int getopt (INT argc, char * const argv [], const char * optstring): optstring does not seem clear. You can check the code later. -1 is returned after the function is executed or fails.

Source program:

/*************************************** * *************** Name: getopt. c ** Author: gzshun ** version: 1.0 ** Date: 2012-01 ** description: getopt test program *** this file may be redistributed under the terms *** of the GNU Public License. **************************************** * *************/# include <stdio. h> # include <stdlib. h> # include <unistd. h> extern char * optarg; extern int optind; extern int o Pterr; extern int optopt; extern int getopt (INT argc, char * const argv [], const char * optstring); # define option_a (1 <0) # define option_ B (1 <1) # define option_c (1 <2) # define option_d (1 <3) # define option_e (1 <4) # define option_f (1 <5) # define option_g (1 <6) # define option_h (1 <7) const char * programe_name = "getopt "; static void usage (void); static int PRS (INT argc, char ** argv, int * opts); static voi D usage (void) {fprintf (stderr, "Usage: % s [Option] \ n "" \ t [-abcdeh] \ n "" \ t [-F digit] [-G String] \ n ", programe_name ); exit (1);} static int PRS (INT argc, char ** argv, int * opts) {int retval, prog_num; char ch; * opts & = 0x00000000; /*************************************** * *************** optstring: "abcdef: G: H" indicates the required option for getopt. abcdeh: the options are not followed by the option parameter F: G: An option is followed by a number, indicating that the option is followed by a parameter. this option parameter can be obtained through the optarg global variable. **************************************** * *************/While (CH = getopt (argc, argv, "abcdef: G: H "))! =-1) {Switch (CH) {Case 'A': * opts | = option_a; break; Case 'B': * opts | = option_ B; break; case 'C': * opts | = option_c; break; Case 'D': * opts | = option_d; break; Case 'E': * opts | = option_e; break; case 'F': * opts | = option_f; printf ("-F optarg = % s \ n", optarg); break; Case 'G': * opts | = option_g; printf ("-G optarg = % s \ n", optarg); break; Case 'H': * opts | = option_h; usage (); break; default: fprintf (stderr, "Our: % s: Invalid o Ption -- '% C' \ n ", programe_name, optopt); exit (1); break ;}} return 0 ;}int main (INT argc, char ** argv) {int I, retval; int opts;/* print the argv array */printf ("before calling getopt \ n") before calling getopt; for (I = 0; I <argc; I ++) {printf ("% s", argv [I]);} printf ("\ n "); /*************************************** * ***************** this function is the most basic and important operation to compile a Linux Command, call the getopt () function in the function to parse the operation options of the command, for example, CP-a-r SRC dstgetopt () to analyze the Parameter options. For details, refer to: (Chapter 21st of advanced programming in UNIX environment communicates with the Network Printer p619) **************************************** * *****************/retval = PRS (argc, argv, & opts); If (retval <0) {exit (1);} printf ("\ n "); /* print the argv array */printf ("after calling getopt \ n") after getopt is called; for (I = 0; I <argc; I ++) {printf ("% s", argv [I]);} printf ("\ n "); /* click here to print the options */printf ("-A \ t set % s \ n", opts & option_a? "Yes": "no"); printf ("-B \ t set % s \ n", opts & option_ B? "Yes": "no"); printf ("-C \ t set % s \ n", opts & option_c? "Yes": "no"); printf ("-d \ t set % s \ n", opts & option_d? "Yes": "no"); printf ("-e \ t set % s \ n", opts & option_e? "Yes": "no"); printf ("-f \ t set % s \ n", opts & option_f? "Yes": "no"); printf ("-g \ t set % s \ n", opts & option_g? "Yes": "no"); printf ("-H \ t set % s \ n", opts & option_h? "Yes": "no"); printf ("\ n "); /*************************************** * ****************** after the getopt operation is completed, the strings in the two argv arrays have been sorted, and the options are placed at the top, while the non-options are ranked at the end, but the original order remains unchanged; why do we need to add this loop, because in many cases we need to add additional parameters, such as the Copy command CP-a-r src1 src2 src3 src4 DST.-A-R is an option, SRC [1-4] DST are the remaining parameters. If you need these parameters, use the following loop to obtain them. **************************************** * ******************/for (I = optind; I <argc; I ++) {printf ("optind = % d \ t: argv [% d] = % s \ n", I, I, argv [I]);} return 0 ;}

Program Execution result 1:

Here, the order is intentionally disrupted. For a clearer view of the getopt usage method

gzshun@ubuntu:~/c/getopt$ ./getopt china -a beijing -b shanghai -c shenzhen -d -f 1234 -g helloBefore calling getopt./getopt china -a beijing -b shanghai -c shenzhen -d -f 1234 -g hello-f optarg=1234-g optarg=helloAfter calling getopt./getopt -a -b -c -d -f 1234 -g hello china beijing shanghai shenzhen-a       set yes-b       set yes-c       set yes-d       set yes-e       set no-f       set yes-g       set yes-h       set nooptind=9        : argv[9]=chinaoptind=10       : argv[10]=beijingoptind=11       : argv[11]=shanghaioptind=12       : argv[12]=shenzhen

Program Execution result 2:

Use the-H option to print command usage

gzshun@ubuntu:~/c/getopt$ ./getopt -hBefore calling getopt./getopt -hUsage:  getopt [OPTION]        [-abcdeh]        [-f digit] [-g string]

I personally like the VI color configuration and paste it to see if it is quite bright:

I am not talented, the above may have a wrong understanding.
Since I recently wrote three Linux commands, I have summarized the gains in the csdn blog. Although this kind of program is cainiao-level, I will record it and wait for me to check it next time, this is efficiency. I hope that Daniel will not despise me. I write this boring program, but it is just a learning attitude.

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.