skolukmar
skolukmar

Reputation: 331

Bash Verify date format

I try to check, if input is correct. The input is correct if looks like YYYY-MM-DD. I try to write a function, but I get failed result.

function reg_exp 
{
    if [[ $1 =~ [0-9]{4}-[0-9]{2}-[0-9]{2} ]]
    then echo "true"
    else echo "false"
    fi
}

>reg_exp 2015-10-20
true

# but for the parameter "2015-10-200" the results is failed....
> reg_exp 2015-10-200
true

Where is the mistake?

Upvotes: 1

Views: 53

Answers (2)

Aserre
Aserre

Reputation: 5062

As your format matches the one of date, you can use it to validate your date instead of using a regex. It will check for leap years and specific number of days per month :

check_date() {
    if date -d "$1" &>/dev/null
        then echo true
    else
         echo false
    fi
}

Upvotes: 1

oconnor0
oconnor0

Reputation: 3234

You are checking only that that pattern exists in your input. To check that the pattern is all of the input, try:

function reg_exp 
{
    if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
    then echo "true"
    else echo "false"
    fi
}

The ^ means beginning of string and the $ means end of string.

Upvotes: 3

Related Questions