验证shell脚本中的日期格式 [英] Validate date format in a shell script
问题描述
我必须创建一个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
date "+%d/%m/%Y" -d "09/99/2013" > /dev/null 2>&1
is_valid=$?
如果您没有获得0,则日期格式无效。
If you do not get 0 then date is in invalid format.
这篇关于验证shell脚本中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!