我正在尝试制作一个 shell 脚本以用作带有 cron 的 HDD 温度警报作业。 cron 作业必须做这些事情:
- 验证现有的 ATA 设备(我正在使用 camcontrol);
- 验证所识别设备的温度(我使用的是 smartctl);
- 将 ATA 设备的温度与常数变量进行比较;
- 如果其中一个设备的温度高于常量,脚本会发送一封电子邮件,其中包含所有 ATA 设备的温度。
我的问题是如何使用第 2 项的结果来完成第 3 项...
我的实际代码是:
# Defines alert temperature
TEMP_MAX=30 #Graus celcius
# Create an array with devices
arrdiscs=($(camcontrol devlist | awk '{print substr($NF, 8, length($NF)-8)}'))
# Get the temperature of the devices
for i in "${arrdiscs[@]}"
do
# Get temperatures
TEMP="$(smartctl -A /dev/$i | egrep ^194 | awk '{print $10}')"
done
如果我使用,我可以回显设备名称和温度:
for i in "${arrdiscs[@]}"
do
TEMP="$(smartctl -A /dev/$i | egrep ^194 | awk '{print $10}')"
echo "[$i]: $TEMP"
done
我尝试过(以及许多其他方法):
for i in "${arrdiscs[@]}"
do
TEMP="$(smartctl -A /dev/$i | egrep ^194 | awk '{print $10}')"
echo "[$i]: $TEMP"
done
echo "ARRAY DISCOS: ${arrdiscs[*]}"
echo "TEMPERATURAS: ${TEMP[*]}"
上面的代码正确打印了“arrdiscs”,但“TEMP”打印为空。
那么...我如何创建一个基于 TEMP 变量的数组,以便我可以验证哪个温度高于 TEMP_MAX?
按照 Etan Reisner 的建议进行了一些更改:
# Defines alert temperature
temp_max=20 #Graus celcius
# Monta array de discos do sistema
arrdiscs=($(camcontrol devlist | awk '{print substr($NF, 8, length($NF)-8)}'))
echo "${arrdiscs[@]}"
alertdiscs=()
for i in "${arrdiscs[@]}"
do
temp=("$(smartctl -A "/dev/$i" | egrep ^194 | awk '{print $10}')")
if [ -z "$temp" ]; then
echo "\$temp is empty"
else
if [ $temp -gt $temp_max ]; then
alertdiscs+=("[$i]: $temp")
echo ${temp[@]}
fi
fi
done
if [ ${#alertdics[@]} -gt 0 ]; then
echo "The following discs were too hot:"
printf '%s\n' "${alertdiscs[@]}"
else
echo "${alertdiscs[@]}"
fi
但是我得到的结果如下:
ada0 ada1 ada2 ada3 da0
33
31
32
30
$temp is empty
[ada0]: 33 [ada1]: 31 [ada2]: 32 [ada3]: 30
变量 temp_max 设置为 20,但没有显示“以下光盘太热:”消息...:(
最佳答案
您可以像这样零碎地创建一个数组:
temps=()
for i in "${arrdiscs[@]}"
do
temps+=("$(smartctl -A "/dev/$i" | egrep ^194 | awk '{print $10}')")
done
echo "${temps[*]}"
话虽这么说,我可能会建议将大部分温度保留在循环本地,并且只将值得警报的温度(和磁盘)存储在适合在最后的消息中使用的数组中。
# Defines alert temperature
temp_max=30 #Graus celcius
alertdiscs=()
for i in "${arrdiscs[@]}"
do
temp=("$(smartctl -A "/dev/$i" | egrep ^194 | awk '{print $10}')")
if [ -n "$temp" ] && [ $temp -gt $temp_max ]; then
alertdiscs+=("[$i]: $temp")
fi
done
if [ ${#alertdiscs[@]} -gt 0 ]; then
echo "The following discs were too hot:"
printf '%s\n' "${alertdiscs[@]}"
fi
关于arrays - bash:如何使用一个数组创建另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29675220/