for循环中变量的嵌套数组

时间:2017-07-01 03:46:05

标签: arrays bash

我是在Bash开始尝试这样做,但我做不到。

示例:

array=("/dev/sda1" "/dev/sdb1")

for i in "${array[@]";do
    space=$(df -H | grep ${array[1]})
done

或者这个:

i=0

for i in ("/dev/sda1" "/dev/sdb1")
    space=$(df -h | grep (($i++)))
done

这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以直接将数组提供给df,如下所示,并避免使用for-loop

df -H "${array[@]}"

但是,如果这是冒险研究bash中的for-loop,那么你可以像下面这样做

for i in "${array[@]}"
do
 df -H "$i" 
 # Well, "${array[@]}" expands to everything in array
 # and i takes each value in each turn.
done

如果您希望使用索引访问数组,那么

for ((i = 0; i < ${#array[@]}; i++)) # This is a c-style for loop
do 
  df -H "${array[i]}" # Note the index i is not prefixed with $
done

修改

检查用量是否超过10GB

# We will usage file which we would use to fill the body of mail
# This file will contain the file system usage
# But first make sure the file is empty before every run
cat /dev/null > /tmp/diskusagereport
for i in "${array[@]}"
do
 usage=$(df -H "$i" | awk 'END{sub(/G$/,"",$3);print $3}')
 if [ "${usage:-0}" -gt 10 ]
 then
  echo "Filesystem : ${i} usage : ${usage}GB is greater than 10GB" >> /tmp/diskusagereport
 fi
done
#finally use the `mailx` client like below

mailx -v -r "from@address.in" -s "Disk usage report" \
      -S smtp="smtp.yourserver.org:port" -S smtp-auth=login \
      -S smtp-auth-user="your_auth_user_here" \
      -S smtp-auth-password='your_auth_password' \
                         to@address.com </tmp/diskusagereport