1

我有一个脚本询问用户以下问题:

read -p "Input time duration of simulation in HH:MM:SS format" -e Time

现在如何确保用户在实际使用变量 $Time 之前为 $Time 输入了正确的表单?

4

2 回答 2

2

我假设您需要检查小时 < 24、分钟 < 60、秒 < 60?

read -p "Input time duration of simulation in HH:MM:SS format " -e Time

while :; do
  if [[ $Time =~ ^([0-9]{2}):([0-9]{2}):([0-9]{2})$ ]]; then
    if (( BASH_REMATCH[3] < 60 ))\
       && (( BASH_REMATCH[2] < 60 ))\
       && (( BASH_REMATCH[1] < 24 )); then
       break
    fi
  fi
  read -p "Wrong format. Please use the HH:MM:SS format " -e Time
done

# Do something with $Time  
于 2012-10-20T08:16:01.953 回答
0

你可以这样测试它:

if [[ $Time =~ ^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$ ]]; then
    echo "format is ok"
else
    echo >&2 "format is wrong"
fi
于 2012-10-11T20:50:30.897 回答