arrays - bash:如何使用一个数组创建另一个数组?

标签 arrays bash shell

我正在尝试制作一个 shell 脚本以用作带有 cron 的 HDD 温度警报作业。 cron 作业必须做这些事情:

  1. 验证现有的 ATA 设备(我正在使用 camcontrol);
  2. 验证所识别设备的温度(我使用的是 smartctl);
  3. 将 ATA 设备的温度与常数变量进行比较;
  4. 如果其中一个设备的温度高于常量,脚本会发送一封电子邮件,其中包含所有 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/

相关文章:

linux - 括号和 ips 之间的所有内容都解析失败

linux - 没有更新以反射(reflect)新文件吗?

c++ - 使用 fstream 向所有用户发送消息

arrays - 替换字符串数组中的特定字符

javascript - 将数组的元素作为 React 中对象的一部分推送

bash - 从 url 运行 bash 脚本时如何获取用户输入?

linux - n 天前从命令行上的给定日期开始

linux - 如何避免并行命名管道的死锁?

javascript - 根据对象属性创建数组

java - 如何查看数组中有多少内存位置已满