验证 shell 脚本中的日期格式 [英] Validate date format in a shell script

查看:71
本文介绍了验证 shell 脚本中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个 Shell 脚本,其中一个参数是 dd/mm/yyyy 格式的日期.我的问题是,如何检查作为参数传递的日期是否真的遵循此日期格式?我尝试使用 grep 命令如下:

I have to create a Shell Script wherein one of the parameters will be the date in the format dd/mm/yyyy. My question is, how can I check if the Date passed as parameter really follows this Date Format? I tried to use the grep command as below:

if echo "$1" | grep -q '^[0-3][0-9]/[0-1][0-9]/[0-9]{4}$'

但它没有给出正确的格式,因为例如日期可以是 33、34、(...),这并不是真正正确的格式.任何人都知道可以真正检查通过的日期是否真的遵循 dd/mm/yyyy 格式?

but it didn't give the correct format because the day for example can be 33, 34, (...), that is not really the correct format. Anyone know something that can really check if the date passed really follows the format dd/mm/yyyy ?

推荐答案

使用 日期

date "+%d/%m/%Y" -d "09/99/2013" > /dev/null  2>&1
 is_valid=$?

日期字符串必须是MM/DD/YYYY";格式.

The date string must be in "MM/DD/YYYY" format.

如果您没有得到 0,则日期格式无效.

If you do not get 0 then date is in invalid format.

这篇关于验证 shell 脚本中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆