Processing of command line options and parameters in Shell

Source: Internet
Author: User
Tags builtin

In Bash, you can use the following three methods to process command lines:ParametersEach method has its own application scenario.
1. perform direct processing, parse $1, $2,..., $ N in sequence, and perform manual processing respectively;
2. getopts to process the single character options (for example,-N 10-F file.txt and other options );
3. getopt can process single character options, or long-option (for example, -- prefix =/Home) Long Options ).
Summary: Generally, manual processing of small Scripts may be enough. getopts can handle the vast majority of cases,GetoptComplex and more powerful.

The following are simple descriptions:

1. Manually process the location parameters
You must know several variables,
* $0: The command itself, equivalent to argv [0] in C/C ++
* $1: The first parameter.
* $2, $3, $4...: four parameters: 2nd, 3, and so on.
* $ # Number of parameters, excluding the command itself
* $ @: List of parameters, excluding the command itself
* $ *: It is the same as $ @, but "$ *" and "$ @" (with quotation marks) are different. "$ *" interprets all parameters as a string, "$ @" is a parameter array.
The manual processing method can meet the majority of simple requirements. The powerful functions can also be constructed with shift. However, the following two methods are recommended when dealing with complex options.
Give an instance (getargs. Sh ):

#! /Bin/bash
If [$ #-LT 1]; then
Echo "error... need ARGs"
Exit 1
Fi
Echo "commond is $0"
Echo "ARGs are :"
For ARG in "$ @"
Do
Echo $ ARG
Done

Run the command:./getargs. Sh 11 22 CC
Commond is./getargs. Sh
ARGs are:
11
22
CC

2. getopts (shell built-in command)
Processing Command Line parameters is similar and complex. For this reason, C provides functions such as getopt/getopt_long, and C ++ boost provides the options library. In shell, getopts and getopt.
Let's talk about the difference between getopts and getopt. getopt is an external binary file, while getopts is Shell builtin.

[Admin @ intlqa142055x ~] $ Type getopt
Getopt is/usr/bin/getopt
[Admin @ intlqa142055x ~] $ Type getopts
Getopts is a shell builtin

Getopts cannot directly process long options (for example, -- prefix =/home)
For how to use getopts, use man Bash to search for getopts.
Getopts has two parameters. The first parameter is a string, including the character and ":". Each character is a valid option. If the character is followed by ":", this character has its own parameters. Getopts obtains these parameters from the command, deletes "-", and assigns it to the second parameter. If it has its own parameter, this parameter is assigned to "optarg. The shell that provides getopts has the built-in optarg variable. getopts modifies this variable.
Here, the variable $ optarg stores the parameters of the corresponding options, while $ optind always stores the location of the next element to be processed in the original $.
While getopts ": A: BC" opt # The first colon indicates that the error is ignored. The colon after the character indicates that the option must have its own parameters.
Code instance (getopts. Sh ):

Echo $ *
While getopts ": A: BC" opt
Do
Case $ opt in
A) echo $ optarg
Echo $ optind ;;
B) echo "B $ optind ";;
C) echo "C $ optind ";;
? ) Echo "error"
Exit 1 ;;
Esac
Done
Echo $ optind
Shift $ ($ optind-1 ))
# With shift $ ($ optind-1), $ * only retains the parameters that remove the option content, and can be followed by normal shell programming.
Echo $0
Echo $ *

Run the command:./getopts. Sh-A 11-B-c
-A 11-B-c
11
3
B 4
C 5
5
./Getopts. Sh

3. getopt (an external tool)
The specific usage can be man getopt.
#-O indicates the short option. Two colons indicate that this option has an optional parameter. The optional parameter must be closely related to the option, such as-CARG rather than-C Arg.
# -- Long indicates the long option
For example, getopt. sh ):

#! /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 -- 'could 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 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 the values of $1, $2... $ n. These values are 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

Run the command:./getopt. Sh -- B-long ABC-a-c33 remain.
Option B, argument 'abc'
Option
Option C, argument '33'
Remaining arguments:
--> 'Remain'

References:

Http://www.cnblogs.com/FrankTan/archive/2010/03/01/1634516.html

Http://www.orczhou.com/index.php/2010/04/linux-shell-getopt/

Http://blog.csdn.net/flowingflying/archive/2010/01/03/5126066.aspx

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.