Steve
Steve

Reputation: 596

Check a user's input is correctly formatted

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

Upvotes: 1

Views: 2935

Answers (1)

devnull
devnull

Reputation: 123448

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

Upvotes: 2

Related Questions