我正在为自定义格式日期验证编写通用脚本。这是脚本
dateformat=$1
d=$2
date "+$dateformat" -d "$d" > /dev/null 2>&1
if [ $? != 0 ]
then
echo "Date $d NOT a valid YYYY-MM-DD date"
exit 1
fi
问题是
sh -x poc_col_val_date.sh "%Y-%m-%d" "2019-11-09"
预期是有效日期,输出也正确sh -x poc_col_val_date.sh "%d-%m-%Y" "2019-11-09"
预期是无效日期,输出是有效日期
答案1
你可以在这里使用perl。这使用了核心模块 Time::Piece。
valid_date() {
# this function returns with the exit status of the perl command
perl -MTime::Piece -se 'Time::Piece->strptime($date, $fmt)' -- -fmt="$1" -date="$2" 2>/dev/null
}
所以
valid_date '%Y-%m-%d' '2019-11-09' && echo Y || echo N # => Y
valid_date '%d/%m/%y' '2019-11-09' && echo Y || echo N # => N
答案2
我用下面的脚本进行了测试,您将了解有效和无效日期
#!/bin/bash
d="2021-03-20"
z="20-03-2021"
date +%Y-%m-%d -d "$d"
if [ $? -eq 0 ]
then
echo "its valid date"
fi
echo "========================="
date +%d-%m-%Y -d "$d"
if [ $? -eq 0 ]
then
echo "its valid date"
fi
echo "========================"
date +%Y-%m-%d -d "$z"
if [ $? -ne 0 ]
then
echo "its not a valid date"
fi
output
2021-03-20
its valid date
=========================
20-03-2021
its valid date
========================
date: invalid date ‘20-03-2021’
its not a valid date