当前位置: 代码迷 >> 综合 >> getopts的使用
  详细解决方案

getopts的使用

热度:83   发布时间:2024-02-24 11:52:55.0

getopts的功能:指定选项option和其规则

举例,编写shell脚本vim testopt.sh:

echo $OPTIND
getopts ":l:m:n:" opt
echo ${opt}的值是$OPTARGecho $OPTIND
getopts ":l:m:n:" opt
echo ${opt}的值是$OPTARGecho $OPTIND
getopts ":l:m:n:" opt
echo ${opt}的值是$OPTARGecho $OPTIND
getopts ":l:m:n:" opt
echo ${opt}的值是$OPTARG

解释:第一个:是屏蔽系统错误(比如illegal option),改由自己处理

后边的每个字母后边的:代表这个选项是必须要值($OPTARG)的,没值的话

通过getopts取到的选项$opt就会被赋值为:了。$OPTIND只指向选项从一开始。

testopt.sh  -l lv  -m mv  -n nv

1

l的值是lv

 

3

-m的值是mv

 

5

-n的值是nv

 

7

?的值是

 

  相关解决方案