Chinaunix首页 | 论坛 | 博客
  • 博客访问: 70365
  • 博文数量: 9
  • 博客积分: 889
  • 博客等级: 军士长
  • 技术积分: 100
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-11 16:50
文章分类
文章存档

2012年(1)

2010年(8)

分类: Python/Ruby

2012-02-12 15:26:15

命令概要

从Shell Script的命令行当中解析参数

getopts optstring name [arg...]

命令描述

optstring列出了对应的Shell Script可以识别的所有参数。比如,如果 Shell Script可以识别-a,-f以及-s参数,则optstring就是afs,如果对应 的参数后面还跟随一个值,则在相应的optstring后面加冒号。比如,a:fs 表示a参数后面会有一个值出现,-a value的形式。另外,getopts执行匹配 到a的时候,会把value存放在一个叫OPTARG的Shell Variable当中。如果 optstring是以冒号开头的,命令行当中出现了optstring当中没有的参数 将不会提示错误信息。

name表示的是参数的名称,每次执行getopts,会从命令行当中获取下一个 参数,然后存放到name当中。如果获取到的参数不在optstring当中列出, 则name的值被设置为?。

命令行当中的所有参数都有一个index,第一个参数从1开始,依次类推。 另外有一个名为OPTIND的Shell Variable存放下一个要处理的参数的index。

例子 
  1. #!/bin/bash
  2. # getopts-test.sh

  3. while getopts :d:s o
  4. do
  5.     case "$o" in
  6.         d)
  7.             echo "d option value is $OPTARG"
  8.             echo "d option index is $(($OPTIND-1))"
  9.             ;;
  10.         s)
  11.             echo "s option..."
  12.             echo "s option index is $(($OPTIND-1))"
  13.             ;;
  14.         [?])
  15.             print "Usage: $0 [-s] [-d value] file ..."
  16.             exit 1
  17.             ;;
  18.     esac
  19. done

运行结果:

$ ./getopts-test.sh -d 8 -s

d option value is 8

d option index is 2

s option...

s option index is 3

阅读(5434) | 评论(1) | 转发(3) |
0

上一篇:Fedora rhythmbox中mp3乱码解决

下一篇:没有了

给主人留下些什么吧!~~

-小Y头-2012-02-15 10:47:23

optstring果然很给力!列出了对应的Shell Script可以识别的所有参数