使用 getopt 命令
getopt 命令在处理命令行选项和参数时非常方便。它能够识别命令行参数,简化解析过程
1. 命令格式
getopt 命令可以接受一系列任意形式的命令行选项和参数,并自动将其转换成适当的格式。
getopt 的命令格式如下:
getopt optstring parameters
例:
$ getopt ab:cd -a -b BValue -cd test1 test2
-a -b BValue -c -d -- test1 test2
$
如果 optstring 未包含你指定的选项,则在默认情况下,getopt 命令会产生一条错误消息:
$ getopt ab:cd -a -b BValue -cde test1 test2
getopt: invalid option -- 'e'
-a -b BValue -c -d -- test1 test2
$
如果想忽略这条错误消息,可以使用 getopt 的-q 选项:
$ getopt -q ab:cd -a -b BValue -cde test1 test2
-a -b 'BValue' -c -d -- 'test1' 'test2'