Getopts is a bash shell built-in command that parses a command-line pass in a shell script, passes it to a function, or passes it to a shell script that is passed to another call (option or parameter, which is explained later, getopts only supports short options, To resolve the long option, refer to getopt).
getopts command syntax:
getopts optstring name [ARG]
Related terms:
Option: GNU-style command options, such as:-x,-y and so on, plus a single letter for the short option;--help for the long option;
parameters for options: Some options must be followed by trailing parameters, such as:-F xxx.conf,xxx.conf parameters called options;
Parameters: The string that is located after the last option, space;
optionstring: A string that matches the option, and each letter in the optionstring corresponds to the option to remove the minus sign (this refers to the short option);
[Arg ]: used to replace positional parameters by getopts parsing, similar to the [email protected] assigned to ARG;
a built-in variable for the optind:getopts that represents the next parameter index to be processed, initialized to 1 each time the shell or shell script executes;
Name:getopts each resolved to an option, the character corresponding to the option is copied to the name variable
Simple explanation of the getopts command:
1.optstring if the letter followed by a colon, indicating that the letter represents an option followed by a parameter, the value of the parameter will be assigned to the OPTARG variable. As contained in test.sh: getopts "I:" name; Then, when executing test.sh-i 1.1.1.1 at the command line, $name = ' i ', $OPTARG =1.1.1.1
Getopts contains two types of error handling modes
Quiet mode:
When the first character of the 2.optstring is a colon, getopts uses quiet mode to report the error (but no error message output), which is typically used in production environments;
3. If you enter an invalid character as an option (a character not included in optstring), will '? ' Assigns a value to the name variable, the character assigned value of the invalid option to the OPTARG variable;
4. If the option requires a parameter to follow, Getopts will assign the colon ":" to the name variable and set the option character Optarg to be found;
In the non-quiet mode:
5. If getopts is not in quiet mode, an invalid option is found, '? ' will be set to the name variable and unset optarg
6. If the option requires a parameter not found, '? ' will be set to Name,optarg will be unset, error message will be printed
Exit Status:
7. If the $OPTERR environment variable value in the shell is 0,getopts, the error message will be printed, even if the first character in optstring is not a colon. The default $opterr value is 1
8.getopts normally resolves positional parameters ($0-$9), but the positional parameters are still resolved correctly when they exceed this range
9. If the option is found (match optionstring) returns True, returns False if the end of the option is encountered or if there is an error
Script instance:
1. Without optional parameters [ARG]
#!/bin/bash
echo "Optind starts at $OPTIND"
While getopts ": Q:p" optname
Do
Case ' $optname ' in
"P")
echo "Option $optname is specified"
;;
"Q")
echo "Option $optname has value $OPTARG"
#shift 1
Shift $ ((OPTIND-2))
;;
"?")
echo "Unknown option $OPTARG"
;;
":")
echo "No argument value for option $OPTARG"
;;
*)
# should not occur
echo "Unknown Error while processing options"
;;
Esac
echo "Optind is now $OPTIND"
Done
Perform:
[Email protected] ~]# bash test_getopts.sh-q aa-p-H
Optind starts at 1
Option Q has value AA
Optind is now 3
Unknown option H
Optind is now 4
2. With optional parameters [ARG]
#!/bin/bash
echo "Optind starts at $OPTIND"
While getopts ": Q:p" optname "-Q Qarg" "-P" "-H"
Do
Case ' $optname ' in
"P")
echo "Option $optname is specified"
;;
"Q")
echo "Option $optname has value $OPTARG"
;;
"?")
echo "Unknown option $OPTARG"
;;
":")
echo "No argument value for option $OPTARG"
;;
*)
# should not occur
echo "Unknown Error while processing options"
;;
Esac
echo "Optind is now $OPTIND"
Done
Perform:
[Email protected] ~]# bash test_getopts.sh
Optind starts at 1
Option Q has value Qarg
Optind is now 2
Option P is specified
Optind is now 3
Unknown option H
Optind is now 4
3. Implement a script that adds a Yum source
#!/bin/bash
#
# descrition:this script would download the Yum repo file from mirrors.163.com and Epel for Centos/redhat Distibute
# Author:gateray Jo
# Mail: [email protected]
Set-e
Prog= ' basename
Arch= ' Uname-m '
Release= ' Lsb_release-r | Sed ' s/.*:[[:space:]]*//'
function usage () {
Cat<<eof
Usage:./${prog} [Options] [ARG]
-h:print the command Help.
-u:specified the BaseURL for Yum Repository, must use WITH-UFN combination.
-f:specified the name of the local repofile (no ". Repo" ext name) which place in/etc/yum.repos.d/, must use WITH-UFN
Combination.
-n:specified the repo ' s name in Xxx.repo file, must use WITH-UFN combination.
-d:specified the URL of repofile which would be download to/etc/yum.repos.d/.
By default, the Nothing options is specified which would download Epel and 163 yum Repofile.
Eof
}
function default () {
major_rel=${release%%.*}
# Download 163 Repofile
printf "Download 163 repofile from mirrors.163.com:\n"
Wget-p/ETC/YUM.REPOS.D Http://mirrors.163.com/.help/centos${major_rel}-base-163.repo
printf "Download Epel repofile from Http://dl.fedoraproject.org.:\ N
if [[$arch = "x86_64"]]; Then
[${major_rel}-eq 5] && RPM-IVH http://dl.fedoraproject.org/pub/epel/5/x86_64/epel-release-5-4.noarch.rpm
[${major_rel}-eq 6] && RPM-IVH http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
Else
[${major_rel}-eq 5] && RPM-IVH http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
[${major_rel}-eq 6] && RPM-IVH http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
Fi
Return $?
}
[$#-eq 0] && default && exit $?
While getopts ": hu:f:n:d:" optname; Do
Case $optname in
"H")
Usage && Exit 0
;;
"U")
U_opt=1
u_arg= $OPTARG
;;
"F")
F_opt=1
u_arg= $OPTARG
;;
"N")
N_opt=1
n_arg= $OPTARG
;;
"D")
Wget-p/ETC/YUM.REPOS.D $OPTARG
Exit $?
;;
"?")
echo "Unknown option $OPTARG"
Usage && exit 1
;;
":")
echo "It is need a option value for $OPTARG"
Usage && exit 1
;;
*)
Echo ' Unknown error! ' && exit 1
;;
Esac
Done
If [$u _opt-eq 1-a $f _opt-eq 1-a $n _opt-eq 1]; Then
if [[${n_arg} =~ '-']]; Then
echo "Invalid value for-n option, \" ${n_arg}\ "is include '-' character."
Exit 1
Fi
Cat >>/etc/yum.repos.d/${f_arg}.repo <<eof
[${n_arg}]
Name=${n_arg}
Baseurl=${u_arg}
Enabled=1
Gpgcheck=0
Eof
Else
Usage && exit 1
Fi
Execution of the script:
1) Print command help
[Email protected] ~]#./load_yum_repo.sh-h
Usage:./load_yum_repo.sh [Options] [ARG]
-h:print the command Help.
-u:specified the BaseURL for Yum Repository, must use WITH-UFN combination.
-f:specified the name of the local repofile (no ". Repo" ext name) which place in/etc/yum.repos.d/, must use WITH-UFN
Combination.
-n:specified the repo ' s name in Xxx.repo file, must use WITH-UFN combination.
-d:specified the URL of repofile which would be download to/etc/yum.repos.d/.
By default, the Nothing options is specified which would download Epel and 163 yum Repofile.
2) Automatic download of 163 and Epel yum source without any option parameters Repofile
[Email protected] ~]#./load_yum_repo.sh
Download 163 repofile from mirrors.163.com:
--2015-04-04 22:23:05--Http://mirrors.163.com/.help/CentOS6-Base-163.repo
Resolving mirrors.163.com ... 123.58.173.106
Connecting to mirrors.163.com|123.58.173.106|:80 ... Connected.
HTTP request sent, awaiting response ... OK
length:2006 (2.0K) [Application/octet-stream]
Saving to: "/etc/yum.repos.d/centos6-base-163.repo"
100%[==========================================================================================>] 2,006--.-K /s in 0.05s
2015-04-04 22:23:05 (39.2 kb/s)-"/etc/yum.repos.d/centos6-base-163.repo" saved [2006/2006]
Download Epel repofile from http://dl.fedoraproject.org.:
Retrieving http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
Warning:/var/tmp/rpm-tmp.wvrcds:header V3 rsa/sha256 Signature, key ID 0608b895:nokey
Preparing ... ########################################### [100%]
1:epel-release ########################################### [100%]
3) Download the repofile from the specified URL
[Email protected] ~]#/load_yum_repo.sh-d Http://mirrors.163.com/.help/CentOS6-Base-163.repo
--2015-04-04 22:13:47--Http://mirrors.163.com/.help/CentOS6-Base-163.repo
Resolving mirrors.163.com ... 123.58.173.106
Connecting to mirrors.163.com|123.58.173.106|:80 ... Connected.
HTTP request sent, awaiting response ... OK
length:2006 (2.0K) [Application/octet-stream]
Saving to: "/etc/yum.repos.d/centos6-base-163.repo"
100%[==========================================================================================>] 2,006--.-K /s in 0.05s
2015-04-04 22:13:47 (40.9 kb/s)-"/etc/yum.repos.d/centos6-base-163.repo" saved [2006/2006]
4) Creating a custom Repofile
[Email protected] ~]#/load_yum_repo.sh-f test-n test-u file:///mnt
[Email protected] ~]# Cat/etc/yum.repos.d/test.repo
[Test]
Name=test
Baseurl=file:///mnt
Enabled=1
Gpgcheck=0
getopts command Learning in the Linux shell-implements a script that adds a Yum source