
#!/bin/sh
REGEX="^[2][0-2]:[0-5][0-9]$"
TIME="21:30"
if [ $TIME = $REGEX ]; then
echo "Worked"
else
echo "Did not work"
fi
我想這與 : 有關,但就我而言,這只是一個不需要轉義序列的常規標誌。
答案1
簡單的=
正規表示式比較是錯誤的。您必須使用=~
, 並且還必須使用雙括號:
if [[ $TIME =~ $REGEX ]]; then
...
也可以看看:https://stackoverflow.com/questions/17420994/bash-regex-match-string
答案2
您也可以查看以下case
聲明:
REGEX="[2][0-2]:[0-5][0-9]"; # Note no placeholders like ^ and $ here
TIME="21:30"
case $TIME in
$REGEX ) echo "Worked" ;; # Note no double quotes around $REGEX for allowing the wildcard matching to happen
* ) echo "Did not work" ;;
esac