Getopts is a built-in command of the shell, typically used to handle shell command-line options, but cannot handle long options (such as--prefix=/home, etc.) directly.
Getopts has 2 parameters, the first parameter is a string, including the character and ":", each character is a valid option, if the character is followed by ":", indicating that the character has its own parameters. The second parameter is used to store the acquired options.
The shell provides 2 built-in variables for getopts:
Optarg: The parameters of the corresponding options are stored;
Optind: Stores the location of the next processing option in the original $*;
Instance:
#!/bin/bashecho $*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;; esacdoneecho $OPTINDshift $ (($OPTIND - 1)) #通过shift $ (($OPTIND - 1)), the $* only retains the parameters to remove the contents of the option, which can then be processed by normal shell programming. echo $0echo $*
Execute command:./getopts.sh-a 11-b-C
-A 11-b-C
11
3
B 4
C 5
5
./getopts.sh
Resources:
http://blog.csdn.net/li385805776/article/details/16981541
Shell processing command-line options getopts