Unix shell脚本中的日期验证(ksh)

时间:2016-09-30 10:30:35

标签: unix

我在Unix shell脚本中验证日期如下:

CheckDate="2010-04-09"
regex="[1-9][0-9][0-9][0-9]-[0-9][0-9]-[0-3][0-9]"

if [[ $CheckDate = *@$regex ]]
then
echo "ok"
else
echo "not ok"
fi 

但是ksh它提供输出不正常..请帮助..我想要输出正常

3 个答案:

答案 0 :(得分:1)

这是我的小脚本(用Solaris 10编写,nawk是强制性的......对不起......)。我知道如果你试图通过发送字母数字来欺骗它,你会在let语句中得到错误。不完美,但它会让你到那里......

#!/usr/bin/ksh

# checks for "-" or "/" separated 3 field parameter...   
if [[ `echo $1 | nawk -F"/|-" '{print NF}'` -ne 3 ]]
then
    echo "invalid date!!!"
    exit 1
fi

# typeset trickery...
typeset -Z4 YEAR
typeset -Z2 MONTH
typeset -Z2 DATE

let YEAR=`echo $1 | nawk -F"/|-" '{print $3}'`
let MONTH=`echo $1 | nawk -F"/|-" '{print $1}'`
let DATE=`echo $1 | nawk -F"/|-" '{print $2}'`
let DATE2=`echo $1 | nawk -F"/|-" '{print $2}'`

# validating the year
# if the year passed contains letters or is "0" the year is invalid...
if [[ $YEAR -eq 0 ]]
then
    echo "Invalid year!!!"
    exit 2
fi

# validating the month
if [[ $MONTH -eq 0 || $MONTH -gt 12 ]]
then
    echo "Invalid month!"
    exit 3
fi

# Validating the date
if [[ $DATE -eq 0 ]]
then
    echo "Invalid date!"
    exit 4
else
    CAL_CHECK=`cal $MONTH $YEAR | grep $DATE2 > /dev/null 2>&1 ; echo $?`
    if [[ $CAL_CHECK -ne 0 ]]
    then
        echo "invalid date!!!"
        exit 5
    else
        echo "VALID DATE!!!"
    fi
fi

答案 1 :(得分:0)

你可以试试这个并操纵

  echo "04/09/2010" | awk  -F '/' '{ print ($1 <= 04 && $2 <= 09 && match($3, /^[0-9][0-9][0-9][0-9]$/)) ? "good" : "bad" }'

  echo "2010/04/09" | awk  -F '/' '{ print ( match($1, /^[0-9][0-9][0-9][0-9]$/) && $2 <= 04 && $3 <= 09 ) ? "good" : "bad" }'

答案 2 :(得分:0)

请查看以下代码作为您的例外情况。

  export checkdate="2010-04-09"
    echo ${checkdate} | grep '^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$'
    if [ $? -eq 0 ]; then
         echo "Date is valid"
     else
          echo "Date is not valid"
     fi