在case语句中使用数字范围

时间:2015-05-02 09:28:42

标签: linux bash shell

我在处理案件方面遇到了麻烦。每次都进入最后一种情况,即*字符。

以下是我正在使用的内容:

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

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

2 个答案:

答案 0 :(得分:5)

使用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

答案 1 :(得分:3)

只需使用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