网站被k申诉,什么是h5开发,在线手机动画网站模板下载安装,推广普通话宣传周使用 getopts 命令 getopt 与 getopts 的不同之处在于#xff0c;前者在将命令行中选项和参数处理后只生成一个输出#xff0c;而后者能够和已有的 shell 位置变量配合默契。 getopts 每次只处理一个检测到的命令行参数。在处理完所有的参数后#xff0c;getopts 会退出并返…使用 getopts 命令 getopt 与 getopts 的不同之处在于前者在将命令行中选项和参数处理后只生成一个输出而后者能够和已有的 shell 位置变量配合默契。 getopts 每次只处理一个检测到的命令行参数。在处理完所有的参数后getopts 会退出并返回一个大于 0 的退出状态码。这使其非常适合用在解析命令行参数的循环中。 getopts 命令的格式如下
getopts optstring variable getopts 命令要用到两个环境变量。如果选项需要加带参数值那么 OPTARG 环境变量保存的就是这个值。 OPTIND 环境变量保存着参数列表中 getopts 正在处理的参数位置。这样在处理完当前选项之后就能继续处理其他命令行参数了。 例子
$ cat extractwithgetopts.sh
#!/bin/bash
# Extract command-line options and values with getopts
#
echo
while getopts :ab:c opt #######while 语句定义了 getopts 命令指定要查找哪些命令行选项以及每次迭代时存储它们的变量名opt。
do case $opt in a) echo Found the -a option ;; b) echo Found the -b option with parameter value $OPTARG;; c) echo Found the -c option ;;*) echo Unknown option: $opt ;; esac
done
exit
$
$ ./extractwithgetopts.sh -ab BValue -c
Found the -a option
Found the -b option with parameter value BValue
Found the -c option
$
getopts 命令有几个不错的特性。可以在参数值中加入空格
$ ./extractwithgetopts.sh -b BValue1 BValue2 -a
Found the -b option with parameter value BValue1 BValue2
Found the -a option
$
另一个好用的特性是可以将选项字母和参数值写在一起两者之间不加空格
$ ./extractwithgetopts.sh -abBValue
Found the -a option
Found the -b option with parameter value BValue
$
getopts 命令能够从-b 选项中正确解析出 BValue 值。除此之外getopts 命令还可以将在命令行中找到的所有未定义的选项统一输出成问号
$ ./extractwithgetopts.sh -d
Unknown option: ?
$
$ ./extractwithgetopts.sh -ade
Found the -a option
Unknown option: ?
Unknown option: ?
$
在处理每个选项时getopts 会将 OPTIND 环境变量值增 1。处理完选项后可以使用 shift 命令和 OPTIND 值来移动参数
$ cat extractoptsparamswithgetopts.sh
#!/bin/bash
# Extract command-line options and parameters with getopts
#
echo
while getopts :ab:cd opt
do case $opt in a) echo Found the -a option ;; b) echo Found the -b option with parameter value $OPTARG;; c) echo Found the -c option ;; d) echo Found the -d option ;; *) echo Unknown option: $opt ;; esac
done
#
shift $[ $OPTIND - 1 ]
#
echo
count1
for param in $
do echo Parameter $count: $param count$[ $count 1 ]
done
exit
$
$ ./extractoptsparamswithgetopts.sh -db BValue test1 test2
Found the -d option
Found the -b option with parameter value BValue
Parameter 1: test1
Parameter 2: test2
$