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

全部博文(14)

文章存档

2008年(14)

我的朋友
最近访客

分类:

2008-07-28 15:38:30

11.4 使用选项
表面上,命令行选项没有什么特别之处。它们紧跟在脚本名称之后出现,与命令行参数一样。而事实上,可以像处理命令行参数一样处理命令行选项。
11.4.1 处理简单选项
在上面的test13脚本中,我们学习了如何使用shift命令处理脚本中提供的命令行参数。也可以使用这种技术处理命令行选项。
在提取每个单独的参数时,可使用case语句确定参数何时被格式化为选项:
$ cat test15
#!/bin/bash
# extracting command line options as parameters
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option";;
-c) echo "Found the -c option" ;;
*) echo "$1 is not an option";;
esac
shift
done
$ ./test15 -a -b -c -d
Found the -a option
Found the -b option
Found the -c option
-d is not an option
$
case语句检查每个参数是否是有效的选项。当找到一个有效选项时,则在case语句中运行适当的命令。
此方法无论选项在命令行中出现的顺序如何都可以工作:
$ ./test15 -d -c -a
-d is not an option
Found the -c option
Found the -a option
$
case语句处理每一个在命令行参数中找到的选项。如果命令行中包含了其他参数,则可以将case语句的catch-all部分包括一些命令以进行处理。
11.4.2 从参数中分离出选项
有时,您可能会遇到一种情况,既要对shell脚本使用选项,又要使用参数。在Linux中达到此目的的标准方法就是使用特殊的字符代码来分隔二者,以便告诉脚本选项于何处结束,以及常规的参数于何处开始。
对于Linux而言,这个特殊的字符是双横线(--)。shell使用双横线表示选项列表的结束。看到双横线后,脚本可安全地将剩下 的命令行参数作为参数处理,而不是将它们当作选项。
要检查双横线,需要做的只是在case语句中添加另一个项目:
$ cat test16
#!/bin/bash
# extracting options and parameters
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option";;
-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
$
此脚本使用break命令使得while循环在遇到双横线时跳出循环。由于我们过早跳出了循环,所以需要另外一个shift命令将双横线从参数变量中提取出来。
对于第一个测试,请尝试使用常规的参数和选项系列:
$ ./test16 -c -a -b test1 test2 test3
Found the -c option
Found the -a option
Found the -b option
test1 is not an option
test2 is not an option
test3 is not an option
$
结果显示,脚本在进行处理时将所有的命令行参数作为选项看待。接下来,尝试相同的内容,但这次使用双横线在命令行上分隔选项和参数:
$ ./test16 -c -a -b -- test1 test2 test3
Found the -c option
Found the -a option
Found the -b option
Parameter #1: test1
Parameter #2: test2
Parameter #3: test3
$
当脚本遇到双横线时,它停止处理选项,并假设命令行上剩余的都是参数。
阅读(717) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~