我正在为 Nagios 编写一个插件来检查安全包的数量,并做一个案例陈述这里。
但整个事情最终变成了一场怪异的秀。我基本上想做的就是说,如果有 1-20 个包会显示此警告,如果有 21 个到无穷个包会显示严重警告等等,但我无法做到,[ -gt 1 ]
甚至无法做到[20-10000]
当应用这些范围时,脚本会以某种不规则的方式运行,并在需要时发出警告,等等。我认为我明白范围在这里实际上是不可能的,我只是想知道为什么它对上面给出的示例有效,但对我却无效。此外,是否有可能以任何方式在案例中包含条件?
最后我终于写出了一个可以完全运行的脚本,但我必须创建 if 条件并将其传递给 case。我只是想知道是否有更简单的方法可以做到这一点而不必这样做。
下面大致就是我尝试做的。最后一部分是我绝望地尝试了大量不同的范围,看看是否有效。
case $SECURITY_PACKAGES in
0)
echo "OK - not bad: There are a total of $TOTAL_PACKAGES packages to upgrade in this server, but none of them are security updates!"
exit 0
;;
[1-20]*)
echo "WARNING - $TOTAL_PACKAGES packages required to upgrade in this server, of which $SECURITY_PACKAGES are security updates"
exit 1
;;
[21-99]|[100-999]|[1000-9999]*)
echo "CRITICAL - $SECURITY_PACKAGES out of $TOTAL_PACKAGES are security updates! Consider upgrading soon!"
exit 2
;;
*) echo "UNKNOWN - I am not sure what's happening now, check later or check server: $TOTAL_PACKAGES to upgrade, $SECURITY_PACKAGES are security updates"
exit 3
;;
esac
答案1
您无法在表达式中轻松表达数字范围-例如,case
模式[1000-9999]
并不意味着1000
到 的数字9999
,但字符1
、0
、0
、范围0-9
、字符9
、9
、9
- 基本上是所有数字。[1-85]
并不意味着1
到 的数字,而是从到 的85
数字,和、 ... 只是从到 的数字。 因此意味着以、、 或-开头的任何内容都会匹配。 改用/ / / / :1
8
5
1
8
[1-20]*
1
2
0
20000000
if
then
elif
else
fi
if (( $SECURITY_PACKAGES == 0 ))
then
echo "OK - not bad: There are a total of $TOTAL_PACKAGES packages to upgrade in this server, but none of them are security updates!"
exit 0
elif (( $SECURITY_PACKAGES <= 20 ))
then
echo "WARNING - $TOTAL_PACKAGES packages required to upgrade in this server, of which $SECURITY_PACKAGES are security updates"
exit 1
elif (( $SECURITY_PACKAGES <= 9999 ))
then
echo "CRITICAL - $SECURITY_PACKAGES out of $TOTAL_PACKAGES are security updates! Consider upgrading soon!"
exit 2
else
echo "UNKNOWN - I am not sure what's happening now, check later or check server: $TOTAL_PACKAGES to upgrade, $SECURITY_PACKAGES are security updates"
exit 3
fi