您的位置:首页 > 运维架构 > Shell

Shell处理用户输入参数----getopts

2013-01-15 15:04 453 查看
特殊变量提醒:

$# 记录命令行参数个数

$* 保存所有参数,并当做单个单词保存

$@ 保存所有参数,当做同一个字符串中的多个独立的单词

getopts 命令格式:

getopts optstring variable

有效字母都会列在optstring中,当前参数保存在 variable中

示例:

#!/bin/bash
while  getopts  :ab:c  opt
do
case  "$opt" in
a)
echo  "Found the -a option";;
b)
echo  "Found the -b option,wiht value  $OPTARG";;
c)
echo  "FOund the -c option";;
*)
echo  "Unknown option :$opt";;
esac
done

测试

# sh test.sh  -a -b test -c
Found the -a option
Found the -b option,wiht value  test
FOund the -c option

# sh test.sh  -d
Unknown option :?

选项字母要求有参数值的时候,在其后加一个冒号;

去掉错误消息的话,在optstring之前加一个冒号;

$OPTARG会保存参数值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Shell getopts $* $# $@