分类: Python/Ruby
2011-06-21 16:07:38
下面的例子可参考:
>cat test4
#!/bin/bash
while getopts "ab:cd:" Option
# b and d take arguments
#
do
case $Option in
a) echo -e "a = $OPTIND";;
b) echo -e "b = $OPTIND $OPTARG";;
c) echo -e "c = $OPTIND";;
d) echo -e "d = $OPTIND $OPTARG";;
esac
done
shift $(($OPTIND - 1))
>sh test4 -a -b foo -cd bar
a = 2
b = 4 foo
c = 4
d = 6 bar
>sh test4 -ab foo
a = 1
b = 3 foo
>sh test4 -a -c
a = 2
c = 3
getopts (Shell内置命令)
处理命令行参数是一个相似而又复杂的事情,为此,C提供了getopt/getopt_long等函数,C++的boost提供了Options库,在shell中,处理此事的是getopts和getopt.
先说一下getopts/getopt的区别吧,getopt是个外部binary文件,而getopts是shell builtin。
[admin@intlqa142055x ~]$ type getopt getopt is /usr/bin/getopt [admin@intlqa142055x ~]$ type getopts getopts is a shell builtin |
echo $* while getopts ":a:bc" opt do case $opt in a ) echo $OPTARG echo $OPTIND;; b ) echo "b $OPTIND";; c ) echo "c $OPTIND";; ? ) echo "error" exit 1;; esac done echo $OPTIND shift $(($OPTIND - 1)) #通过shift $(($OPTIND - 1))的处理,$*中就只保留了除去选项内容的参数,可以在其后进行正常的shell编程处理了。 echo $0 echo $* |