"Go" Bash shell command line Options/parameter handling

Source: Internet
Author: User

Original URL: http://www.cnblogs.com/FrankTan/archive/2010/03/01/1634516.html

0. Introduction


When writing a program, you often have to handle command-line arguments, and this article describes the command-line processing under bash.

Options and Parameters:

As the next command line:

./test.sh-f Config.conf-v--prefix=/home


We call-f as the option, it requires a parameter, namely config.conf,-V is also an option, but it does not require parameters.

--prefix We call it a long option, that is, the option itself is more than one character, it also needs a parameter, with an equal sign connection, of course, the equal sign is not necessary,/home can be written directly behind the--prefix, that is,--prefix/home, more restrictions are described later.
In bash, there are three ways to handle command-line arguments, each of which has its own application scenario.

* Manual Handling method
* Getopts
* getopt

Let's discuss these three ways of handling in turn.

1. Manual Handling method


In manual processing, you first need to know a few variables, or the above command behavior example:

* $:./test.sh, which is the command itself, equivalent to the argv[0 in C + +]
* $:-F, the first parameter.
* $2:config.conf
* $ $, $4 ... Analogy
* The number of $# parameters, excluding the command itself, the $ #为4 in the example above.
* [email protected]: The list of the parameters themselves, also does not include the command itself, as in the example above is-F config.conf-v--prefix=/home
* $*: Same as [email protected], but "$*" and "[email protected]" (quoted) and different, "$*" interprets all the parameters as a string, and "[email protected]" is an array of parameters. As shown in the following example:


1 #!/bin/bash
2
3 for Arg in "$*"
4 Do
5 echo $arg
6 Done
7
8 for Arg in "[Email protected]"
9 Do
Ten echo $arg
One-Done
12


Executed./test.sh-f config.conf-n 10 will print:

-F config.conf-n #这是 "$*" output

-F #以下为 [email protected] Output

Config.conf

-N

10



Therefore, the processing of these variables is handled in a manual manner. Because manual processing is highly dependent on the location of the arguments that you pass on the command line, it is generally used only to handle simpler parameters. Such as

./test.sh 10

and rarely used./test-n 10 this way with options. Typical uses are:

#!/bin/bash

if [x$1! = x]
Then
#... With parameters
Else
Then
#... No parameters
Fi



Why use X$1! = x This way to compare? Imagine this way of comparing:


If [-N $] #$1 is not empty

However, if the user does not pass the parameter, $ $ is empty, then it becomes [-n], so you need to add a helper string to compare.

Manual processing can meet most of the simple requirements, with shift use can also construct a powerful function, but in order to deal with complex options, the following two methods are recommended.

2. getopts/getopt


Processing command-line arguments is a similar and complex thing, and for this reason, C provides functions such as Getopt/getopt_long,
The boost from C + + provides the options library, in which the getopts and getopt are dealt with in the shell.

Getopts and getopt function similarly but not exactly the same, where Getopt is a standalone executable, and getopts is built by bash.

Let's take a look at the typical use of parameter passing:

*./test.sh-a-b-c: Short options, no parameters required for each option
*./TEST.SH-ABC: The short option, like the effect of the previous method, simply writes all the options together.
*./test.sh-a Args-b-C: Short option, where-a requires parameters, and-b-c does not need parameters.
*./test.sh--a-long=args--b-long: Long option

Let's look at getopts first, it doesn't support the long option.

Using Getopts is simple:
Code

#test. Sh

#!/bin/bash

While getopts "A:BC" Arg #选项后面的冒号表示该选项需要参数
Do
Case $arg in
A
echo "A ' s arg: $OPTARG" #参数存在 $OPTARG
;;
b
echo "B"
;;
C
echo "C"
;;
?) #当有不认识的选项的时候arg为?
echo "Unkonw argument"
Exit 1
;;
Esac
Done



Now you can use:
./test.sh-a Arg-b-C
Or
./test.sh-a ARG-BC
to load it.
It should be said that the vast majority of scripts use this function, if you need to support long options and optional parameters, then you need to use getopt.
Here is an example of getopt:


#!/bin/bash

# A Small Example program for using the new Getopt (1) program.
# This program would only work with Bash (1)
# Similar program using the TCSH (1) script language can 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 the We use ' "[email protected]" ' to let each command-line parameter expand to a
# separate word. The quotes around ' [email protected] ' is essential!
# We need TEMP as the ' eval set--' would nuke the return value of getopt.

#-o represents a short option, two colons indicates that the option has an optional parameter, the optional parameter must be close to the option
#如-carg and cannot be-c arg
#--long = Long option
# "[Email protected]" explained above
#-N: Information on Error
#--: An example is better understood:
What will you do #我们要创建一个名字为 the "-F" directory?
# mkdir-f #不成功, because-f is parsed by mkdir as an option, you can use
# mkdir---F so-F will not be used as an option.

Temp= ' Getopt-o ab:c::--long a-long,b-long:,c-long:: \
-N ' example.bash '--"[email protected]" '

If [$?! = 0]; Then echo "Terminating ..." >&2; Exit 1; Fi

# Note the quotes around ' $TEMP ': they is essential!
#set rearrange the order of the parameters, that is, the value of the change $1,$2 ... $n, the values are rearranged in getopt
Eval set--"$TEMP"

#经过getopt的处理, the specific options are processed below.

While true; Do
Case "$" in
-a|--a-long) echo "Option a"; shift;
-b|--b-long) echo "Option B, argument \ ' $ '"; Shift 2;;
-c|--c-long)
# C has an optional argument. As we is in quoted mode,
# an empty parameter would be generated if it optional
# argument is not found.
Case "$" in
"") echo "Option C, no argument"; Shift 2;;
*) echo "Option C, argument \ ' $ '"; Shift 2;;
ESAC;;
--) shift; break;;
*) echo "Internal error!"; Exit 1;;
Esac
Done
echo "Remaining arguments:"
For Arg do
Echo '--' \ ' $arg ';
Done



For example, we use
./test-a-B Arg arg1-c
As you can see, the command line has more than one arg1 parameter, and after passing getopt and set, the command lines become:
-a-b Arg-c--arg1
The arg1 pointing to the-a,$2 pointing to the-b,$3 point arg,$4 to the-c,$5 pointing to the--, is placed at the end.

3. Summary

General Small Script manual processing perhaps enough, getopts can handle most of the situation, getopt more complex, more powerful.
If you have any questions, please note that we appreciate it.

"Go" Bash shell command line Options/parameter handling

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.