Chinaunix首页 | 论坛 | 博客
  • 博客访问: 87275
  • 博文数量: 14
  • 博客积分: 1570
  • 博客等级: 上尉
  • 技术积分: 400
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-19 09:23
文章分类

全部博文(14)

文章存档

2008年(14)

我的朋友
最近访客

分类:

2008-07-29 11:19:30

11.4.3处理值的参数
有时,选项还需要额外的参数值。在这种情况下,命令行寻找类似以下内容:
$ ./testing -a test1 -b -c -d test2
脚本必须能够检测到命令行选项何时需要额外的参数并能对其进行恰当地传递。如以下示例所示:
$ cat test17
#!/bin/bash
# extracting command line options and values
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option";;
-b) param="$2"
echo "Found the -b option, with parameter value $param"
shift 2;;
-c) echo "Found the -c option";;
--) shift
break;;
*) echo "$1 is not an option";;
esac
shift
done
count=1
for param in "$@"
do
echo "Parameter #$count: $param"
count=$[ $count + 1 ]
done
$ ./test17 -a -b test1 -d
Found the -a option
Found the -b option, with parameter value test1
-d is not an option
在这个示例中,case语句定义了要处理的三个选项。-b选项需要额外的参数值。因为被处理的参数是$1,而额外的参数值位于$2中(由于所有参数在接受处理时都被切换了一次)。只需要从$2变量中提取出参数值。当然,由于我们对此选项使用了两个参数点,所以还需要用shift命令切换两个位置。
虽然只使用了最基本的功能,但此代码可以无须考虑选项顺序而正常工作(只需要记住对每个选项应用恰当的选项参数):
$ ./test17 -b test1 -a -d
Found the -b option, with parameter value test1
Found the -a option
-d is not an option
现在,您应该能够在shell脚本中处理命令行选项了,但还有一些限制。例如,此方法不能应用将多个选项结合为一个参数:
$ ./test17 -ac
-ac is not an option
$
在Linux中,将多个选项结合是非常常见的操作,而如果您的脚本要成为用户友好的脚本,则还需要为用户提供这一功能才好。幸运的是,还有另一种方法可以帮助我们处理选项。
阅读(849) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~