#Bash 的 getopts 命令
getopts OPTSTRING NAME [ARG]...
功能
解析选项参数。
getopts每次解析一个参数,将其放入$NAME变量中,然后将参数索引的变量OPTIND加一。
- 选项附带的参数会存入
OPTARG变量中- 如果解析到
PTSTRIN中不包含的选项,$NAME变量会被设为?。- 每次调用 shell 或 shell 脚本时,
OPTIND都会被初始化为 1。
类型
Bash 内置命令。
参数
OPTSTRING- 选项字符串;用冒号(:)后缀表示选项需要附带参数NAME- 接收选项的变量名称ARG- 要解析的参数列表;默认为$@(当前命令的全部参数)
#示例
#!/usr/bin/bash
while getopts "ab:c" OPT; do # 支持 -a -b -c 三个选项,其中 -b 需要附带参数
case $OPT in
a)
echo "选项 -a"
;;
b)
echo "选项 -b,参数是 $OPTARG"
;;
c)
echo "选项 -c"
;;
esac
done
shift $((OPTIND - 1)) # 提取剩余参数
echo 剩余参数:$@
运行结果:
$ ./demo.sh -c -b hello world
选项 -c
选项 -b,参数是 hello
剩余参数:world
#相关命令
| 命令 | 说明 |
|---|---|
| getopt | 解析命令行参数 |
#推荐阅读
#手册
getopts: getopts optstring name [arg ...]
Parse option arguments.
Getopts is used by shell procedures to parse positional parameters
as options.
OPTSTRING contains the option letters to be recognized; if a letter
is followed by a colon, the option is expected to have an argument,
which should be separated from it by white space.
Each time it is invoked, getopts will place the next option in the
shell variable $name, initializing name if it does not exist, and
the index of the next argument to be processed into the shell
variable OPTIND. OPTIND is initialized to 1 each time the shell or
a shell script is invoked. When an option requires an argument,
getopts places that argument into the shell variable OPTARG.
getopts reports errors in one of two ways. If the first character
of OPTSTRING is a colon, getopts uses silent error reporting. In
this mode, no error messages are printed. If an invalid option is
seen, getopts places the option character found into OPTARG. If a
required argument is not found, getopts places a ':' into NAME and
sets OPTARG to the option character found. If getopts is not in
silent mode, and an invalid option is seen, getopts places '?' into
NAME and unsets OPTARG. If a required argument is not found, a '?'
is placed in NAME, OPTARG is unset, and a diagnostic message is
printed.
If the shell variable OPTERR has the value 0, getopts disables the
printing of error messages, even if the first character of
OPTSTRING is not a colon. OPTERR has the value 1 by default.
Getopts normally parses the positional parameters, but if arguments
are supplied as ARG values, they are parsed instead.
Exit Status:
Returns success if an option is found; fails if the end of options is
encountered or an error occurs.