2018/03/08

March 08 2018 Thursday

Weather:cloudy
一、需求:
用shell腳本判斷輸入的日期是否合法。就是判斷日期是都是真實的日期,好比20170110就是合法日期,20171332就不合法。shell

[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
本站公眾號
   歡迎關注本站公眾號,獲取更多信息