假设用户进食时间:
read -p "Enter the start time you want to start(hh:mm:ss) " user_start_time
和正则表达式:
timePattern="[0-2][0-3]:[0-5][0-9]:[0-5][0-9]"
如果我这样做:
if [ "$user_start_time" == "$timePattern" ]
#or if [ "$user_start_time" =~ "$timePattern" ]
then
echo "in if"
else
echo "in else"
fi
它不验证......作为新手,我理解 int
的比较或string
但我们该怎么做time
(日期也在那里,但是 date -d
解决了很多问题)
There is this question too 但无法理解接受的答案!!
最佳答案
对于正则表达式匹配,您需要在 BASH 中使用 =~
运算符而不是 ==
。所以像这样使用它:
[[ "$user_start_time" =~ $timePattern ]] && echo "in if" || echo "in else"
您还需要删除正则表达式变量周围的引号 $timePattern
关于regex - 使用正则表达式模式验证 bash 中的用户输入时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821920/