Shell脚本与案例模式错误

时间:2017-02-07 04:58:27

标签: bash shell switch-statement

出于某些原因,我没有在此脚本中使用更高的数字模式。

#!/bin/bash
#
# guess_my_number.bash - my favorite number

echo "Can you guess my favorite number???"

echo -e -n "\n\n\033[32m Pick a number between 0 and 100 > "
read num
case $num in

  [0-6] )               echo "You're close...but too low" ;;
  [8-14] )              echo "You're close...but too high" ;;
  [15-100] )            echo "You're nowhere near my favorite number...sorry, try again" ;;
  7 )                   echo "YOU GUESSED MY FAVORITE NUMBER!" ;;
  * )                   echo "You didn't pick a number between 1 and 100!" ;;

esac

如果我将[8-14]更改为[8..14],如果我在运行脚本时键入8,则会得到回应响应但是9-100中的任何其他数字都会给出通配符回应响应。如果它[8-14]它也给了我通配符响应。就像我说的那样[0-6]模式给出了它的回声,7也是如此。

这里有什么问题?

3 个答案:

答案 0 :(得分:0)

这适用于......

if [ "$num" = "7" ]; then
  echo -e "\n\n\033[33m YOU GUESSED MY FAVORITE NUMBER!\n\n"
else
  echo "That's not my number. HINT: Red XIII"
  while [ "$num" != "7" ]; do
    echo -e -n "\n\033[32m Pick again > "
    read num
      if [ "$num" = "7" ]; then
        echo -e "\n\n\033[33m YOU GUESSED MY FAVORITE NUMBER!\n\n"
      fi
  done
fi

不太适合我的目的。

答案 1 :(得分:0)

#!/bin/bash
#
# guess_my_number.bash - my favorite number

echo "Can you guess my favorite number???"

echo -e -n "\n\n\033[32m Pick a number between 0 and 100 > "
read num
case $num in

 [0-6] )               echo "You're close...but too low" ;;
 [8-9] )            echo "You're close...but too high" ;;
 1[0-4])             echo "You're close...but too high" ;;
 [1-9][0-9] )            echo "You're nowhere near my favorite number...sorry, try again" ;;
  7 )                   echo "YOU GUESSED MY FAVORITE NUMBER!" ;;
  * )                   echo "You didn't pick a number between 1 and 100!" ;;

esac

答案 2 :(得分:0)

正如在其他链接中所建议的那样,case只能执行模式匹配而不能执行arithmetice扩展。 这意味着您可以使用[0-6]中的范围,其中正则表达式将匹配0-6范围内的任何单个字符,但范围[8-14]不是有效模式。

如果您坚持使用案例,那么您的示例应该是这样的:

case $num in
  ([0-6])                 echo "You're close...but too low" ;;
  ([8-9]|1[0-4])          echo "You're close...but too high" ;;
  (1[5-9]|[2-9][0-9]|100) echo "You're nowhere near my favorite number...sorry, try again" ;;
  7 )                     echo "YOU GUESSED MY FAVORITE NUMBER!" ;;
  * )                     echo "You didn't pick a number between 1 and 100!" ;;
esac  

模式(1 [5-9] | [2-9] [0-9] | 100)正则表达式意味着:

1[5-9] : 15-16-17-18-29
[2-9][0-9] : Each number of first [] with one number of second [] = range 20-99
100 : Literally 100
PS: The | is used as OR operator.

由于这种情况的行为,为了比较数字,首选使用if-then-else:

if [ "$num" -ge 0 ] && [ "$num" -le 6 ]; then
  echo "...."
elif [ "$num" -ge 8 ] &&  [ "$num" -le 14 ]; then
  echo "...."
elif [ "$num" -ge 15 ] &&  [ "$num" -le 100 ]; then
  echo "...."
elif [ "$num" -eq 7 ] 
  echo "...."
else
  echo "You didn't pick a number between 1 and 100!"
fi