用户输入的日期格式验证在bash [英] user input date format verification in bash

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

问题描述

所以我试图写在bash一个简单的脚本,在要求用户输入日期
以下格式(YYYY-MM-DD)。不幸的是我就死在第一步,这是验证输入的是正确的格式。我试图用日期,没有运气(因为它返回实际当前日期)。我想使这个尽可能简单。谢谢您的帮助!

So I'm trying to write a simple script in bash that asks user for input date in following format (YYYY-dd-mm). Unfortunately I got stuck on first step, which is verifying that input is in correct format. I tried using 'date' with no luck (as it returns actual current date). I'm trying to make this as simple as possible. Thank you for your help!

推荐答案

使用正则表达式:

if [[ $date =~ ^[0-9]{4}-[0-3][0-9]-[0-1][0-9]$ ]]; then

或使用bash水珠:

if [[ $date == [0-9][0-9][0-9][0-9]-[0-3][0-9]-[0-1][0-9] ]]; then

请注意,此正则表达式将接受像日期9999-00-19 这是不正确的日期。所以,你检查它的正确性可能与此正则表达式后,你应该确认该号码是正确的。

Please note that this regex will accept a date like 9999-00-19 which is not a correct date. So after you check its possible correctness with this regex you should verify that the numbers are correct.

IFS='-' read -r year day month <<< "$date"

这将使数字到 $年 $日 $每月变量。

This will put the numbers into $year $day and $month variables.

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

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