How does Shell obtain parameters?
When writing a shell script, you often need to obtain parameters from the outside, for example:
$ sh demo.sh a
So how can we upload the above parameter A to the shell program.
$0 $1... $10, where $0 is the name of the shell program, $1, $2... they are the first parameter and the second parameter... our demo. SH:
$ cat demo.sh#! /bin/bashcat << EOF Usage: sh $0 $1EOF$ sh demo.sh a Usage: sh demo.sh a
Parameters starting with $ include:
$0: program name
$ #: Number of variables
[Email protected]: All variables, namely, $1... $, excluding the program name.
This is a problem. When many parameters are used by others in your program, the interaction is not very good. Others have to remember the location and role of each parameter in the script, which will be very troublesome. You can add a prompt, for example
$ sh demo.sh -a A -b B -c C
How can this be implemented? There are two ways to achieve this:shift
Andgetopts
$ cat demo.sh #! /bin/bashwhile [ $# -gt 0 ];do case $1 in -a) echo "-a----$2" shift ;; -b) echo "-b----$2" shift ;; -c) echo "-c----$2" shift ;; esac shiftdone$ sh demo.sh -a A -b B -c C-a----A-b----B-c----C
getopts
The function simplifies the processing of the preceding options. Let's take a look at its usage.
The first parameter of the function: a string of valid option letters ·:
The parameter must be provided.getopts
The function places the parameters inOPTARG
The other variable isOPTIND
Indicates the index value of the next parameter to be processed.
The second parameter of the function: variable name.getopts
When called, the variable name is updated.getopts
When a valid option is not found, this variable is set as a question mark. The specific implementation is as follows:
#! /Bin/bashwhile getopts A: B: C: OPT; docase $ opt INA) echo "-A ---- $ optarg"; B) echo "-B ---- $ optarg ";; c) echo "-C ---- $ optarg ";;?) Echo "$ OPT is an invalid option"; esacdone $ sh demo. sh-a-B-c-d-a ---- a-B ---- B-c ---- cdemo. SH: Illegal option -- d -- error message output by getopts? Is an invalid option -- the script determines the output error message. Here we set-D option?
However, getopts does not support the long option.getopt
You canman
Below:
Name
Getopt-Parse Command Options (enhanced)
It can be seen from the basic explanation that it is an enhanced versiongetopts
, Althoughgetopts
It has more than one second, but the power of theory is far inferior.getopt
.