getopts使用样例
时间:2005-07-15 来源:xwfang
具体使用方法请参考getopts的在线文档(man getopts).
使用getopts命令读取unix格式选项
UNIX格式选项指如下格式的命令行参数:
command -options parameters
使用格式:
getopts option_string variable
具体使用方法请参考getopts的在线文档(man getopts).
示例如下:
#newdate
if [ $# -lt 1 ]
then
date
else
while getopts mdyDHMSTjJwahr OPTION
do
case $OPTION
in
m) date '+%m ';; # Month of Year
d) date '+%d ';; # Day of Month
y) date '+%y ';; # Year
D) date '+%D ';; # MM/DD/YY
H) date '+%H ';; # Hour
M) date '+%M ';; # Minute
S) date '+%S ';; # Second
T) date '+%T ';; # HH:MM:SS
j) date '+%j ';; # day of year
J) date '+%y%j ';;# 5 digit Julian date
w) date '+%w ';; # Day of the Week
a) date '+%a ';; # Day abbreviation
h) date '+%h ';; # Month abbreviation
r) date '+%r ';; # AM-PM time
?) echo "Invalid option $OPTION";;
esac
done
fi
$ newdate -J
94031
$ newdate -a -h -d
Mon
Jan
31
$ newdate -ahd
Mon
Jan
31
$
示例程序:复制程序
# Syntax: duplicate [-c integer] [-v] filename
# where integer is the number of duplicate copies
# and -v is the verbose option
COPIES=1
VERBOSE=N
while getopts vc: OPTION
do
case $OPTION
in
c) COPIES=$OPTARG;;
v) VERBOSE=Y;;
?) echo "Illegal Option"
exit 1;;
esac
done
if [ $OPTIND -gt $# ]
then
echo "No file name specified"
exit 2
fi
shift `expr $OPTIND -1`
FILE=$1
COPY=0
while [ $COPIES -gt $COPY ]
do
COPY=`expr $COPY + 1`
cp $FILE ${FILE}${COPY}
if [ VERBOSE = Y ]
then
echo ${FILE}${COPY}
fi
done
$ duplicate -v fileA
fileA1
$ duplicate -c 3 -v fileB
fileB1
fileB2
fileB3