十年专注于品牌网站建设 十余年专注于网站建设_小程序开发_APP开发,低调、敢创新、有情怀!
南昌百恒网络微信公众号 扫一扫关注
小程序
tel-icon全国服务热线:400-680-9298,0791-88117053
扫一扫关注百恒网络微信公众号
扫一扫打开百恒网络微信小程序

百恒网络

南昌百恒网络

介绍Linux中更高级getopts命令的用法

百恒网络 2017-09-16 6410

昨天为大家介绍了getopt 命令的使用方法,今天南昌网络公司-百恒网络小编将为大家介绍一种更高级 getopts命令的用法,供大家参考,学习。 getopts命令(注意是复数)内建于bash shell。它跟近亲getopt看起来很像,但多了一些扩展功能。

与getopt不同,前者将命令行上选项和参数处理后只生成一个输出,而getopts命令能够和已有的shell参数变量配合默契。

每次调用它时,它一次只处理命令行上检测到的一个参数。处理完所有的参数后,它会退出并返回一个大于0的退出状态码。这让它非常适合用解析命令行所有参数的循环中。

getopts命令的格式如下:

getopts optstring variable

optstring值类似于getopt命令中的那个。有效的选项字母都会列在optstring中,如果选项字母要求有个参数值,就加一个冒号。要去掉错误消息的话,可以在optstring之前加一个冒号。getopts命令将当前参数保存在命令行中定义的variable中。

getopts命令会用到两个环境变量。如果选项需要跟一个参数值,OPTARG环境变量就会保存这个值。OPTIND环境变量保存了参数列表中getopts正在处理的参数位置。这样你就能在处理完选项之后继续处理其他命令行参数了。

下面百恒网络小编为大家举个使用getopts命令的例子,大家可以简单了解一下。

$ cat test19.sh

#!/bin/bash

# simple demonstration of the getopts command

#

echo

while getopts :ab:c opt

do

case "$opt" in

a) echo "Found the -a option" ;;

b) echo "Found the -b option, with value $OPTARG";;

c) echo "Found the -c option" ;;

*) echo "Unknown option: $opt";;

esac

done

$

$ ./test19.sh -ab test1 -c

Found the -a option

Found the -b option, with value test1

Found the -c option

$

while语句定义了getopts命令,指明了要查找哪些命令行选项,以及每次迭代中存储它们 的变量名(opt)。

你会注意到在本例中case语句的用法有些不同。getopts命令解析命令行选项时会移除开头的单破折线,所以在case定义中不用单破折线。

getopts命令有几个好用的功能。对新手来说,可以在参数值中包含空格。

$ ./test19.sh -b "test1 test2" -a

Found the -b option, with value test1 test2

Found the -a option

$

另一个好用的功能是将选项字母和参数值放在一起使用,而不用加空格。

$ ./test19.sh -abtest1

Found the -a option

Found the -b option, with value test1

$

getopts命令能够从-b选项中正确解析出test1值。除此之外,getopts还能够将命令行上找到的所有未定义的选项统一输出成问号。

$ ./test19.sh -d

Unknown option: ?

$

$ ./test19.sh -acde

Found the -a option

Found the -c option

Unknown option: ?

Unknown option: ?

$

optstring中未定义的选项字母会以问号形式发送给代码。

getopts命令知道何时停止处理选项,并将参数留给你处理。在getopts处理每个选项时,它会将OPTIND环境变量值增一。在getopts完成处理时,你可以使用shift命令和OPTIND值来移动参数。

$ cat test20.sh

#!/bin/bash

# Processing options & 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 value $OPTARG" ;;

c) echo "Found the -c option" ;;

d) echo "Found the -d option" ;;

*) echo "Unknown option: $opt" ;;

esac

done

#

shift $[ $OPTIND - 1 ]

#

echo

count=1

for param in "$@"

do

echo "Parameter $count: $param"

count=$[ $count + 1 ]

done

#

$

$ ./test20.sh -a -b test1 -d test2 test3 test4

Found the -a option

Found the -b option, with value test1

Found the -d option

Parameter 1: test2

Parameter 2: test3

Parameter 3: test4

$

现在你就拥有了一个能在所有shell脚本中使用的全功能命令行选项和参数处理工具。

关于更高级的 getopts命令的使用方法,南昌网络公司-百恒网络就为大家介绍到这里了,如果还有哪些不太明白的地方,可倒回去再看一遍,或者来电咨询我们。此外,如有需要网站建设、微信开发、APP开发等方面的服务的朋友,欢迎来电和我们联系,百恒将随时为您效劳!

400-680-9298,0791-88117053
扫一扫关注百恒网络微信公众号
扫一扫打开百恒网络小程序

欢迎您的光顾,我们将竭诚为您服务×

售前咨询 售前咨询
 
售前咨询 售前咨询
 
售前咨询 售前咨询
 
售前咨询 售前咨询
 
售前咨询 售前咨询
 
售后服务 售后服务
 
售后服务 售后服务
 
备案专线 备案专线
 
×