1

I'm trying to validate a user's input when they enter a date into my bash script.

The correct format should be YYYY-MM-DD HH:MM:SS

What I have so far is this, but it's not quite right.

read -p "-" datetime
if [[ $datetime ! "*[^2000-2100]-[^01-12]-[^10-31] [^00-24]:[^00-60]:[^00-60]*" ]]
  then
    echo "Not a date"
fi
1
  • Hmmm... 2100-02-31 24:60:60 doesn't sound like a valid date/time to me... Even if the regex matching did work that way... Commented Dec 2, 2013 at 12:29

1 Answer 1

2

You could say:

if ! date -d "$datetime" >/dev/null 2>&1; then
  echo "Not a date"
fi

Using regexp isn't really recommended, but if you insist you could say:

if [[ "$datetime" != 2[0-1][0-9][0-9]-[0-1][0-9]-[0-3][0-9]\ [0-2][0-9]:[0-6][0-9]:[0-6][0-9] ]]; then
  then
    echo "Not a date"
fi
Sign up to request clarification or add additional context in comments.

8 Comments

@Steve Yes, better to use date rather than using regexp to parse date.
You know, this is crazy clever, because you can put it anything like "2 weeks friday 10pm" and it understands it.
@Steve Yup, it'll essentially validate everything that's considered good by date.
Yeah tried that, says it's more complex than they can easily list on the man page.
@MikeD I guess it wasn't obvious -- the objective of posting the regex version was an attempt to demonstrate the problem with the way OP was trying to use the regex.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.