BASH Shell Command Line option/parameter Processing

Source: Internet
Author: User

Options and parameters:

For example, the following command line:

./Test. Sh-F config. conf-v-Prefix =/home

We call-f an 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. More limitations are described after the mask.
In Bash, you can use the following three methods to process command line parameters. Each method has its own application scenario.

* Manual processing
* Getopts
* Getopt

The three processing methods are discussed in sequence.

1. Manual Handling

In the manual processing method, you must first know several variables, or the above command behavior example:

* $0:./test. Sh, that is, the command itself, equivalent to argv [0] in C/C ++
* $1:-F, 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, "$ @" is a parameter array. For example:

1 #! /Bin/bash
2
3 For ARG in "$ *"
4 do
5 echo $ ARG
6 done
7
8 For ARG in "$ @"
9 do
10 echo $ ARG
11 done
12

Execute./test. Sh-F config. conf-N 10 to print:

-F config. conf-N 10 # This is the output of "$ *"

-F # output of $ @ below

Config. conf

-N

10

Therefore, manual processing is the processing of these variables. 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

The./test-N 10 option is rarely used. Typical usage:

#! /Bin/bash

If [x $1! = X]
Then
#... Parameters available
Else
Then
#... No Parameters
Fi

Why use x $1! = X to compare? Imagine this comparison:

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

However, if $1 is null when the user does not pass the parameter, it will become [-N]. Therefore, an auxiliary string must be added for comparison.

Manual processing can meet the majority of simple needs, and can also build powerful functions with shift, but we recommend the following two methods to deal with complex options.

2. getopts/getopt

Processing Command Line parameters is similar and complex. Therefore, C provides functions such as getopt/getopt_long,
C ++'s boost provides the options library. In Shell, getopts and getopt are used to handle the issue.

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. They just 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: Long Option

Let's first look at getopts, which does not support the long option.

Getopts is very simple:
Code

# Test. Sh

#! /Bin/bash

While getopts "A: BC" Arg # The colon after the option indicates that the option requires Parameters
Do
Case $ ARG in
A)
Echo "A's Arg: $ optarg" # The parameter exists in $ optarg
;;
B)
Echo "B"
;;
C)
Echo "C"
;;
?) # When there are unrecognized options, What Is Arg?
Echo "unkonw argument"
Exit 1
;;
Esac
Done

Now you can use:
./Test. Sh-A Arg-B-c
Or
./Test. Sh-A Arg-BC
.
It should be said that most scripts can use this function. If you need to support long options and optional parameters, you need to use getopt.
The following is an example of getopt:

#! /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
# 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
# Separate word. The quotes around '$ @' are essential!
# We need temp as the 'eval set-'wocould nuke the return value of getopt.

#-O indicates the short option. Two colons indicate that this option has an optional parameter, which must be closely related to the option.
# For example,-CARG instead of-C Arg
#-Long indicates the long option
# "$ @" Explained above
#-N: error message
#-: An example is better understood:
# What do you do if you want to create a directory named "-F?
# Mkdir-F # failed, because-F will be parsed as an option by mkdir, 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 values, which have been rearranged in getopt
Eval set-"$ Temp"

# After getopt processing, the specific options are processed below.

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

For example, we use
./Test-A-B Arg arg1-C
As you can see, 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 to-, and the extra arg1 points to the end.

3. Summary

Generally, manual processing of small Scripts may be enough. getopts can handle the vast majority of cases. getopt is more complex and powerful.
If you have any questions, please be grateful.

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.