May 05, 2004

getopt example

getopt 是 shell 裡抓參數的好工具
例: getopt abc:d: 容許參數 -a -b -c -d, -c and -d 後面要接參數

#!/bin/sh
set - `getopt abc:d: $*`
while true
do
case $1 in
-a)
echo option -a
shift
;;
-b)
echo option -b
shift
;;
-c)
echo option -c=$2
shift 2
;;
-d)
echo option -d=$2
shift 2
;;
--)
shift
break
;;
*)
echo "error!"
exit 1
;;
esac
done

執行結果
# ./go -a
option a
# ./go -c jack
option -c=jack
# ./go -b -c jack
option -b
option -c=jack
# ./go -b -c test -d
getopt: option requires an argument -- d
option -b
option -c=test
(使用後面要加參數的 option 會提示)
# ./go -b -c test -f
getopt: invalid option -- f
option -b
option -c=test
(使用未支援的參數會提示)

Posted by pank at May 5, 2004 05:30 PM
Comments
Post a comment













Remember personal info?