在case语句中使用数字范围[duplicate]

时间:2021-06-23 10:22:41

This question already has an answer here:

这个问题在这里已有答案:

I'm facing trouble in getting the cases executed. Every time, it goes to the last case i.e. * characters.

在执行案件方面我遇到了麻烦。每次,它都转到最后一种情况,即*字符。

Here's what I'm using:

这是我正在使用的:

case $used_space in
    [1-84])
        echo "OK - $used_space% of disk space used."
        exit 0
        ;;
    [85])
        echo "WARNING - $used_space% of disk space used."
        exit 1
        ;;
    [86-100]*)
        echo "CRITICAL - $used_space% of disk space used."
        exit 2
        ;;
    *)
        echo "$used_space% of disk space used."
        exit 3
        ;;
esac

How can I change my case statement to work with numeric ranges?

如何更改我的case语句以使用数字范围?

2 个解决方案

#1


With bash and case:

使用bash和case:

case $used_space in
  [1-9]|[1-7][0-9]|8[0-4]) # range 1-84
    echo "OK - $used_space% of disk space used."
    exit 0
    ;;
  85)
    echo "WARNING - $used_space% of disk space used."
    exit 1
    ;;
  8[6-9]|9[0-9]|100)        # range 86-100
    echo "CRITICAL - $used_space% of disk space used."
    exit 2
    ;;
  *)
    echo "$used_space% of disk space used."
    exit 3
     ;;
esac

#2


Just use series of if-s, like this:

只需使用if-s系列,如下所示:

if [[ "$used_space" -le 84 && "$used_space" -ge 1 ]]
then
    echo "OK - $used_space% of disk space used."
    exit 0
elif [[ "$used_space" -eq 85 ]]
then
    echo "WARNING - $used_space% of disk space used."
    exit 1
elif [[ "$used_space" -gt 85 && "$used_space" -le 100 ]]
then
    echo "CRITICAL - $used_space% of disk space used."
    exit 2
else
    echo "$used_space% of disk space used."
    exit 3
fi

#1


With bash and case:

使用bash和case:

case $used_space in
  [1-9]|[1-7][0-9]|8[0-4]) # range 1-84
    echo "OK - $used_space% of disk space used."
    exit 0
    ;;
  85)
    echo "WARNING - $used_space% of disk space used."
    exit 1
    ;;
  8[6-9]|9[0-9]|100)        # range 86-100
    echo "CRITICAL - $used_space% of disk space used."
    exit 2
    ;;
  *)
    echo "$used_space% of disk space used."
    exit 3
     ;;
esac

#2


Just use series of if-s, like this:

只需使用if-s系列,如下所示:

if [[ "$used_space" -le 84 && "$used_space" -ge 1 ]]
then
    echo "OK - $used_space% of disk space used."
    exit 0
elif [[ "$used_space" -eq 85 ]]
then
    echo "WARNING - $used_space% of disk space used."
    exit 1
elif [[ "$used_space" -gt 85 && "$used_space" -le 100 ]]
then
    echo "CRITICAL - $used_space% of disk space used."
    exit 2
else
    echo "$used_space% of disk space used."
    exit 3
fi