判断输入的日期是否正确的shell脚本
今儿个讲得是判断输入的日期是否正确,有利用到我们之前03这个例子中的函数
下面是代码
#!/bin/sh
#valid-date--Validatesadate,takingintoaccountleapyearrules.
exceedsDaysInMonth()
{
case$(echo$1|tr'[:upper:]''[:lower:]')in
jan*)days=31;;feb*)days=28;;
mar*)days=31;;apr*)days=30;;
may*)days=31;;jun*)days=30;;
jul*)days=31;;aug*)days=31;;
sep*)days=30;;oct*)days=31;;
nov*)days=30;;dec*)days=31;;
*)echo"$0:Unknownmonthname$1">&2;exit1
esac
if[$2-lt1-o$2-gt$days];then
return1
else
return0#thedaynumberisvalid
fi
}
isLeapYear()
{
year=$1
if["$((year%4))"-ne0];then
return1#nope,notaleapyear
elif["$((year%400))"-eq0];then
return0#yes,it'saleapyear
elif["$((year%100))"-eq0];then
return1
else
return0
fi
}
##Beginmainscript
if[$#-ne3];then
echo"Usage:$0monthdayyear">&2
echo"Typicalinputformatsare832002">&2
exit1
fi
#Normalizedateandsplitbackoutreturnedvalues
if[$?-eq1];then
exit1#errorconditionalreadyreportedbynormdate
fi
monthnoToName()
{
#Setsthevariable'month'totheappropriatevalue
case$1in
01|1)monthd="Jan";;02|2)monthd="Feb";;
03|3)monthd="Mar";;04|4)monthd="Apr";;
05|5)monthd="May";;06|6)monthd="Jun";;
07|7)monthd="Jul";;08|8)monthd="Aug";;
09|9)monthd="Sep";;10)monthd="Oct";;
11)monthd="Nov";;12)monthd="Dec";;
*)echo"$0:Unknownnumericmonthvalue$1">&2;exit1
esac
return0
}
monthnoToName$1
month="$monthd"
day="$2"
year="$3"
if!exceedsDaysInMonth$month"$2";then
if["$month"="Feb"-a"$2"-eq"29"];then
if!isLeapYear$3;then
echo"$0:$3isnotaleapyear,soFebdoesn'thave29days">&2
exit1
fi
else
echo"$0:baddayvalue:$monthdoesn'thave$2days">&2
exit1
fi
fi
echo"Validdate:$newdate"
exit0
分析:
1)首先判断用户输入的参数个数是否正确,接着case$1in语句判断月份是否合理。
2)monthnoToName函数之前出现在我们之前的第03个脚本案例中,用来转换输入的数字日期为字符串。
3)exceedsDaysInMonth用来判断天数是否超过对应月的最大天数,紧跟着if["$month"="Feb"-a"$2"-eq"29"];thenif!isLeapYear$3;then用来判断闰年2月的特殊情况
4)总体的感觉是脚本还是很紧凑的,特别是在判断闰年与2月的关系的那段代码,有点意思。
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短