March 08 2018 Thursday
Weather:cloudy
1、需求:
用shell脚本判断输入的日期是否合法。就是判断日期是都是真实的日期,比如20170110就是合法日期,20171332就不合法。
[root@Dasoncheng sbin]# cat a.sh
#!/bin/bash
if [ "$#" -ne 1 ] || [ "${#1}" -ne 8 ];
then
echo "Usage:bash $0 yyyymmdd"
exit 1
fi
aa=$1
ay=${aa:0:4}
am=${aa:4:2}
ad=${aa:6:2}
if `echo $ad | grep -q "^0"`;
then
ad=`echo $ad |sed 's/^0//g'`
fi
if `cal "$am" "$ay" &>/dev/null`;
then
if `cal "$am" "$ay" | grep -wq "$ad"`;
then
echo "It is ok!"
else
echo "Error: Please input a right date !"
fi
else
echo "Error: Please input a right date of month and year !"
fi
answer referred
#!/bin/bash
#check date
if [ $# -ne 1 ] || [ ${#1} -ne 8 ]
then
echo "Usage: bash $0 yyyymmdd"
exit 1
fi
datem=$1
year=${datem:0:4}
month=${datem:4:2}
day=${datem:6:2}
if echo $day|grep -q '^0'
then
day=`echo $day |sed 's/^0//'`
fi
if cal $month $year >/dev/null 2>/dev/null
then
daym=`cal $month $year|egrep -v "$year|Su"|grep -w "$day"`
if [ "$daym" != "" ]
then
echo ok
else
echo "Error: Please input a wright date."
exit 1
fi
else
echo "Error: Please input a wright date."
exit 1
fi