网站建设集群化的必要东莞公司注册
news/
2025/10/4 6:53:32/
文章来源:
网站建设集群化的必要,东莞公司注册,企业怎么做网站建设,购买营销型网站使用 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
$
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/926731.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!