Input parameter handling for shell scripts

Source: Internet
Author: User

Processing of parameter processing-shell incoming parameters

1. The number of arguments passed to the script by $# 2. $* displays all parameters passed to the script in a single string. Unlike positional variables, this option parameter can exceed 9 3. The script runs the current process ID number 4. $! The process ID number 5 of the last process running in the background. [Email protected] and $ #相同, but use quotation marks and return each parameter 6 in quotation marks. $-Displays the current options used by the shell, which is the same as the SET command function 7. $? Displays the exit status of the last command. 0 means there is no error, and any other value indicates an error.

Variable meaning:

$ A script name $ "Location parameter #1 $-$9 positional parameter #2-#9 ${10} positional parameter #10 ${#*} The number of command-line arguments passed to the script ${#@} The number of command-line arguments passed to the script? return value


Process ID (PID) of the script

$-passed to the script in the flag (using set) $_ the last parameter of the previous command $! Process ID (PID) of the last job running in the background


When using the shell processing parameter processing is a basic module, so today found a simple and understandable article for reference, as a template for future shell parameters processing, we recommend the use of getopts form of parameter processing.

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, is 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, such as the above example is-f config.conf-v--prefix=/home * $*: And [email protected] the same, but "$*" and "[ Email protected] "(quoted) and different," $* "interprets all parameters as a string, and" [email protected] "is an array of parameters.

As shown in the following example:

#!/bin/bashfor arg in "$*" does echo $arg donefor arg in "[email protected]" does echo $arg done

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/bashif [X$1! = x]then # ... There are parameters Elsethen # ... No parameter 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.

*************************************************************************************************************** ***************

Shift is really simple, is to move the argument list left, shift once the leftmost parameter is removed, and then
The original $ $ has now become $ $.

The shift can also be followed by a number that indicates how many parameters to remove (by default, only one), such as
Shift 3 is the move out of the 3 parameters, then the original $4 becomes the current $.

Eval is to execute the command again by executing the following arguments once, and then doing the necessary permutations. As an example:
Myfile= "Cat MYFILE"
Echo $MYFILE # Output:cat MYFILE
Eval $MYFILE # Output:contents of MYFILE

Let's give a more detailed example:
#!/bin/bash
# Evalit
echo "Total number of arguments passed: $#"
echo "The process ID:

"eCho"L asT aR gumeNT :"$(eval eCho/

#)
To run the script:
$./evalit Alpha Bravo Charlie
Output as follows:
Total number of arguments Passed:3
The process id:780
Last Argument:charlie

Read file
For i in ' Cat abc.txt '
Do
Echo $i
Done


Input parameter handling for shell scripts

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.