Confirmation of entering user data input date in bash

So, I'm trying to write a simple script in bash that asks the user for the input date in the following format (YYYY-dd-mm). Unfortunately, I am stuck in the first step, which checks that the input is in the correct format. I tried using the "date" with no luck (since it returns the actual current date). I try to make it as simple as possible. Thanks for the help!

+5
date bash validation
Sep 11 '13 at 18:44
source share
2 answers

Using regex:

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

or bash globs:

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

Note that this regular expression will accept a date of type 9999-00-19 , which is not a valid date. Therefore, after checking the validity of this regular expression, you must make sure that the numbers are correct.

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

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

+20
Sep 11 '13 at 18:46
source share
 date -d "$date" +%Y-%m-%d 

The latter is a format, -d allows you to enter an input date. If it is erroneous, it will return an error, which can be sent in bit by bit; if it is fixed, it will return the date.

Format modifiers can be found in the date man 1 date page man 1 date . Here is an example with an array of three dates:

 dates=(2012-01-34 2014-01-01 2015-12-24) for Date in ${dates[@]} ; do if [ -z "$(date -d $Date 2>/dev/null)" ; then echo "Date $Date is invalid" else echo "Date $Date is valid" fi done 

Just be careful: typing man date on Google, while some NSFW results may appear at work;)

+1
Nov 21 '16 at 10:49
source share



All Articles