检查用户的输入格式是否正确

时间:2013-12-02 10:23:44

标签: linux bash unix

我正在尝试在用户的bash脚本中输入日期时验证用户的输入。

正确的格式应为YYYY-MM-DD HH:MM:SS

到目前为止我所拥有的是这一点,但它并不完全正确。

read -p "-" datetime
if [[ $datetime ! "*[^2000-2100]-[^01-12]-[^10-31] [^00-24]:[^00-60]:[^00-60]*" ]]
  then
    echo "Not a date"
fi

1 个答案:

答案 0 :(得分:2)

你可以说:

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

不建议使用regexp,但如果你坚持要说:

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
相关问题