




已阅读5页,还剩4页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Small getopts tutorial incompleteWhen you want to parse commandline arguments in a professional way, getopts is the tool of choice. Unlike its older brother getopt (note the missing s!), its a shell builtin command. The advantage isyou dont need to hand your positional parameters through to an external programgetopts can easily set shell variables you can use for parsing (impossible for an external process!)you dont have to argue with several getopt implementations which had buggy concepts in the past (whitespaces, )getopts is defined in POSIXSome other methods to parse positional parameters (without getopt(s) are described in: How to handle positional parameters.Note that getopts is not able to parse GNU-style long options (-myoption) or XF86-style long options (-myoption)!DescriptionTerminologyIts useful to know what were talking about here, so lets see Consider the following commandline:mybackup -x -f /etc/mybackup.conf -r ./foo.txt ./bar.txtAll these are positional parameters, but you can divide them into some logical groups:-x is an option, a flag, a switch: one character, indroduced by a dash (-)-f is also an option, but this option has an additional argument (argument to the option -f): /etc/mybackup.conf. This argument is usually separated from its option (by a whitespace or any other splitting character) but thats not a must, -f/etc/mybackup.conf is valid.-r depends on the configuration. In this example, -r doesnt take arguments, so its a standalone option, like -x./foo.txt and ./bar.txt are remaining arguments without any option related. These often are used as mass-arguments (like for example the filenames you specify for cp(1) or for arguments that dont need an option to be recognized because of the intended behaviour of the program (like the filename argument you give your text-editor to open and display - why would one need an extra switch for that?). POSIX calls them operands.To give you an idea about why getopts is useful: The above command line could also read likemybackup -xrf /etc/mybackup.conf ./foo.txt ./bar.txtwhich is very hard to parse by own code. getopts recognized all the common option formats.The option flags can be upper- and lowercase characters, and of course digits. It may recognize other characters, but thats not recommended (usability and maybe problems with special characters).How it worksIn general you need to call getopts several times. Each time it will use the next positional parameter (and a possible argument), if parsable, and provide it to you. getopts will not change the positional parameter set if you want to shift it, you have to do it manually after processing:shift $(OPTIND-1)# now do something with $Since getopts will set an exit status of FALSE when theres nothing left to parse, its easy to use it in a while-loop:while getopts .; do .donegetopts will parse options and their possible arguments. It will stop parsing on the first non-option argument (a string that doesnt begin with a hyphen (-) that isnt an argument for any option infront of it). It will also stop parsing when it sees the - (double-hyphen), which means end of options.Used variablesvariabledescriptionOPTINDHolds the index to the next argument to be processed. This is how getopts remembers its own status between invocations. Also usefull to shift the positional parameters after processing with getopts. OPTIND is initially set to 1, and needs to be re-set to 1 if you want to parse anything again with getoptsOPTARGThis variable is set to any argument for an option found by getopts. It also contains the option flag of an unknown option.OPTERR(Values 0 or 1) Indicates if Bash should display error messages generated by the getopts builtin. The value is initialized to 1 on every shell startup - so be sure to always set it to 0 if you dont want to see annoying messages!getopts also uses these variables for error reporting (theyre set to value-combinations which arent possible in normal operation).Specify what you wantThe base-syntax for getopts is:getopts OPTSTRING VARNAME ARGS.where:OPTSTRINGtells getopts which options to expect and where to expect arguments (see below)VARNAMEtells getopts which shell-variable to use for option reportingARGStells getopts to parse these optional words instead of the positional parametersThe option-stringThe option-string tells getopts which options to expect and which of them must have an argument. The syntax is very simple every option character is simply named as is, this example-string would tell getopts to look for -f, -A and -x:getopts fAx VARNAMEWhen you want getopts to expect an argument for an option, just place a : (colon) after the proper option flag. If you want -A to expect an argument (i.e. to become -A SOMETHING) just do:getopts fA:x VARNAMEIf the very first character of the option-string is a : (colon), which normally would be nonsense because theres no option letter preceeding it, getopts switches to the mode silent error reporting. In productive scripts, this is usually what you want (handle errors yourself and dont get disturbed by annoying messages).Custom arguments to parseThe getopts utility parses the positional parameters of the current shell or function by default (which means it parses $).You can give your own set of arguments to the utility to parse. Whenever additional arguments are given after the VARNAME parameter, getopts doesnt try to parse the positional parameters, but these given words.This way, you are able to parse any option set you like, here for example from an array:while getopts :f:h opt $MY_OWN_SET; do .doneA call to getopts without these additional arguments is equivalent to explicitly calling it with $:getopts . $Error ReportingRegarding error-reporting, there are two modes getopts can run in:verbose modesilent modeFor productive scripts I recommend to use the silent mode, since everything looks more professional, when you dont see annoying standard messages. Also its easier to handle, since the failure cases are indicated in an easier way.Verbose Modeinvalid optionVARNAME is set to ? (quersion-mark) and OPTARG is unsetrequired argument not foundVARNAME is set to ? (quersion-mark), OPTARG is unset and an error message is printedSilent Modeinvalid optionVARNAME is set to ? (question-mark) and OPTARG is set to the (invalid) option characterrequired argument not foundVARNAME is set to : (colon) and OPTARG contains the option-character in questionUsing itA first exampleEnough said - action!Lets play with a very simple case: Only one option (-a) expected, without any arguments. Also we disable the verbose error handling by preceeding the whole option string with a colon (:):#!/bin/bash while getopts :a opt; do case $opt in a) echo -a was triggered! &2 ; ?) echo Invalid option: -$OPTARG &2 ; esacdoneI put that into a file named go_test.sh, which is the name youll see below in the examples.Lets do some tests:Calling it without any arguments$ ./go_test.sh$Nothing happened? Right. getopts didnt see any valid or invalid options (letters preceeded by a dash), so it wasnt triggered.Calling it with non-option arguments$ ./go_test.sh /etc/passwd$Again nothing happened. The very same case: getopts didnt see any valid or invalid options (letters preceeded by a dash), so it wasnt triggered.The arguments given to your script are of course accessible as $1 - $N.Calling it with option-argumentsNow lets trigger getopts: Provide options.First, an invalid one:$ ./go_test.sh -bInvalid option: -b$As expected, getopts didnt accept this option and acted like told above: It placed ? into $opt and the invalid option character (b) into $OPTARG. With our case statement, we were able to detect this.Now, a valid one (-a):$ ./go_test.sh -a-a was triggered!$You see, the detection works perfectly. The a was put into the variable $opt for our case statement.Of course its possible to mix valid and invalid options when calling:$ ./go_test.sh -a -x -b -c-a was triggered!Invalid option: -xInvalid option: -bInvalid option: -c$Finally, its of course possible, to give our option multiple times:$ ./go_test.sh -a -a -a -a-a was triggered!-a was triggered!-a was triggered!-a was triggered!$The last examples lead us to some points you may consider:invalid options dont stop the processing: If you want to stop the script, you have to do it yourself (exit in the right place)multiple identical options are possible: If you want to disallow these, you have to check manually (e.g. by setting a variable or so)An option with argumentLets extend our example from above. Just a little bit:-a now takes an argumenton an error, the parsing exits with exit 1#!/bin/bash wh
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 公司组织滑雪策划方案
- 2025年物流与供应链管理考试卷及答案
- 2025年现代文学与书法艺术考试试题及答案
- 2025年企业文化与内部管理的考核试卷及答案
- 2025年品牌传播与市场联系考核考试试卷及答案
- 2025年可持续发展与环境政策基础知识考试卷及答案
- 2025年媒体传播与社会学习研究考试试卷及答案
- 2025年计算机网络与信息安全课程考试题及答案
- 2025年材料科学与工程专业综合能力测试卷及答案
- 2025年初中历史学科教育考试试题及答案
- 工业管道工程工程量清单项目设置及计价
- 港口集团绩效考核方案
- 基于MATLAB的控制系统仿真及应用-第5章-基于MATLABSimulink的控制系统建模与仿真课件
- 一二次深度融合成套柱上断路器汇报课件
- 解冻记录表(标准模版)
- 初中数学北师大八年级下册(2023年修订) 因式分解岷阳王冬雪提公因式法教学设计
- 金属非金属矿山安全规程
- 生活饮用水游离余氯方法验证报告
- DB32∕T 186-2015 建筑消防设施检测技术规程
- C-TPAT反恐知识培训ppt课件
- 巡检培训课件.ppt
评论
0/150
提交评论