星期二, 五月 15, 2007

bash getopt

先看一下几个简单的例子,就可以了解 getopt 大致怎样使用了:
sh$ args=`getopt abc:d -a -b -c opt`
sh$ echo $args
-a -b -c opt --
sh$ args=`getopt -l long1,long2: abc:d -a -b -c opt1 --long1 opt2 arg1 arg2`
sh$ echo $args
-a -b -c 'opt1' --long1 -- 'opt2' 'arg1' 'arg2'
sh$ args=`getopt -l long1,long2: abc:d -a -b -c opt1 --long2 opt2 arg1 arg2`
sh$ echo $args
-a -b -c 'opt1' --long2 'opt2' -- 'arg1' 'arg2'
那么在脚本中,则通常可以这样:
args=`getopt abc:d $*`
echo $args
一个比较完整的例子如下:
args=`getopt -l help,item:items-list: c:h:m:i:I: $*`
if [ $? -gt 0 ]; then
strerr="Invalid options"
echo "$strerr" >&2
logger -it "$strerr"
exit 1
fi

for i in $args; do
case $i in
-c) shift; community=$1; shift;;
-h) shift; host=$1; shift;;
-m) shift; mailto=$1; shift;;
-i|--item)
shift
if [ -n "$items" ]; then
items=`echo -e "$items\n$1"`
else
items="$1"
fi
shift
;;
-I|--items-list)
shift; ilist=$1; shift;;
--help)
shift
echo "useage: $PROGRAM [-c|-h|-m] [--item|--help]
-c community
-h host
-m mailto
-i|--item item_map, 'community host' map
--help, print this message"
exit 0
;;
esac
done

没有评论: