找到你要的答案

Q:Using numeric ranges in a case statement [duplicate]

Q:在case语句中使用数字范围[复制]

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 $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语句以数值范围工作?

answer1: 回答1:

With bash and 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

Bash和案例:

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
answer2: 回答2:

Just use series of if-s, like this:

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

只使用一系列的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
linux  bash  shell