Getopt/getopts: command line option/parameter processing in Bash

Source: Internet
Author: User

Getopt/getopts: command line option/parameter processing in Bash 0. When writing a program, you must always process command line parameters. This article describes the command line Processing Method in Bash. Options and parameters: for example, the next command line: [vb]. /test. sh-f config. conf-v -- prefix =/home we call-f as the option. It requires a parameter, that is, config. conf,-v is also an option, but it does not need a parameter. -- Prefix is called a long option, that is, the option itself contains more than one character. It also requires a parameter to connect with an equal sign. Of course, the equal sign is not required./home can be directly written after -- prefix, that is, -- prefix/home. We will talk about more limitations after masks. In bash, you can use the following three methods to process command line parameters. Each method has its own application scenario. The following describes the three processing methods in sequence. 1. manual processing: in manual processing, you must first know several variables, or the preceding Command Behavior example: $0 :. /test. sh, that is, the command itself, which is equivalent to argv [0] $1:-f in C/C ++, the first parameter. $2: config. conf $3, $4... and so on. $ # Number of parameters, excluding the command itself. In the preceding example, $ # is 4. $ @: list of parameters, excluding the command itself. For example,-f config. conf-v -- prefix =/home $ *: it is the same as $ @, but "$ *" and "$ @" (with quotation marks) are different, "$ *" interprets all parameters as a string, and "$ @" is a parameter array. For example: [vb] #! /Bin/bash for arg in "$ *" do echo $ arg done for arg in "$ @" do echo $ arg done execution. /test. sh-f config. conf-n 10 will print:-f config. conf-n 10 # This is the output of "$ *" # below is the output of $ @-f config. conf-n10 so the way to handle these variables is done manually. Because manual processing is highly dependent on the location of the parameters you pass on the command line, it is generally only used to process simple parameters. For example, "./test. sh 10" is rarely used./test-n 10. Typical usage: [vb] #! /Bin/bash # if [-n "$1"], parameter is not blank if ["$1 "! = ""] Then #... else then #... no parameter fi manual processing method can meet the majority of simple needs, with shift can also build a powerful function, but to deal with complex options, we recommend that you use the following two methods. 2. getopts/getopt is similar and complex to process command line parameters. Therefore, C provides functions such as getopt/getopt_long, and C ++ boost provides the Options library, in shell, getopts and getopt are used to handle the problem. getopts and getopt functions are similar but not identical. getopts is an independent executable file, while getopts is built in Bash. Let's take a look at the typical usage of parameter passing :. /test. sh-a-B-c: short option. parameters are not required for each option. /test. sh-abc: short options, which have the same effect as the previous method, but write all options together .. /Test. sh-a args-B-c: short option, where-a requires a parameter while-B-c does not .. /Test. sh -- a-long = args -- B-long: Let's first look at getopts, which does not support the long option. Getopts is very simple: -- test. sh [vb] #! /Bin/bash # The colon after the option indicates that this option requires the parameter while getopts "a: bc" arg do case $ arg in) # The parameter exists in $ OPTARG echo "a's arg: $ OPTARG"; B) echo "B"; c) echo "c ";;?) # When there are unrecognized options, What Is arg? Echo "unkonw argument" exit 1; esac done can now be used :. /test. sh-a arg-B-c or. /test. sh-a arg-bc. It should be said that most scripts can use this function. To support long options and optional parameters, you need to use getopt. The following is an example of getopt: [vb] #! /Bin/bash # A small example program for using the new getopt (1) program. # This program will only work with bash (1) # An similar program using the tcsh (1) script language can be found # as parse. tcsh # Example input and output (from the bash prompt ):#. /parse. bash-a par1 'another arg '-- c-long' wow! *\? '-Cmore-B "very long" # Option a # Option c, no argument # Option c, argument 'more' # Option B, argument 'very long' # Remaining arguments: # --> 'par1' # --> 'another arg '# --> 'Wow! *\? '# Note that we use' "$ @" 'to let each command-line parameter expand to a # separate word. The quotes around' $ @ 'are essential! # We need TEMP as the 'eval set -- 'could nuke the return value of getopt. #-o indicates the short option. Two colons indicate that this option has an optional parameter, optional parameters must be followed by the option # For example-carg, but not-c arg # -- long indicates the long option # "$ @" explained above #-n: error message # --: for example, it is better understood: # What do you do if we want to create a directory named "-f? # Mkdir-f # failed, because-f will be parsed by mkdir as an option, then you can use # mkdir ---f so that-f will not be used as an option. TEMP = 'getopt-o AB: c: -- long a-long, B-long:, c-long: \-n' example. bash '-- "$ @"' if [$?! = 0]; then echo "Terminating..."> & 2; exit 1; fi # Note the quotes around '$ TEMP': they are essential! # Set will rearrange the Parameter order, that is, change $1, $2... $ n value. These values are rearranged in getopt by eval set -- "$ TEMP" # processed by getopt. The specific options are as follows. While true; do case "$1" in-a | -- a-long) echo "Option a"; shift;-B | -- B-long) echo "Option B, argument \ '$ 2' "; shift 2;-c | -- c-long) # c has an optional argument. as we are in quoted mode, # an empty parameter will be generated if its optional # argument is not found. case "$2" in "") echo "Option c, no argument"; shift 2; *) echo "Option c, argument \ '$2 '"; shift 2; esac; --) shift; Break; *) echo "Internal error! "; Exit 1; esac done echo" Remaining arguments: "for arg do echo '-->'" \ '$ arg' "; done is used for example. /test-a-B arg arg1-c. You can see that the command line contains an arg1 parameter. After getopt and set, the command line is changed: -a-B arg-c -- arg1 $1 points to-a, $2 points to-B, $3 points to arg, $4 points to-c, $5 points --, the extra arg1 is put to the end. 3. Summary: leopard tail.

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.