无法遍历for循环中的所有元素

时间:2019-08-12 08:35:12

标签: shell loops for-loop

我想ssh到多个远程服务器并检查raid的状态是否为只读。

我为此编写了一个for循环,并且for循环仅使用列表中的最后一个elemnet。它不是从第一个元素,第二个元素等开始迭代的,

  for i in $(cat /home/priyashree/server.txt);do
     machine_ip=$(getent hosts $i | awk {'print $1'})
     machine_info="${i},${machine_ip}"
     machine_new_ip="$(echo ${machine_info}|cut -d, -f2)"
     echo ${machine_new_ip}
  done


 for machineip in $machine_new_ip;do
      raid_status=$(ssh -o StrictHostKeyChecking=no $machineip mount | grep -e '/dev/md2'| cut -d'(' -f2| cut -d, -f1) 
      echo "Raid status for machine $machine_new_ip is $raid_status"
    done```

$machine_new_ip has a list of IP as below
aa.bb.cc.dd
xx.zz.ee.ff

The 2nd for loop will only ssh to the 2nd element (xx.zz.ee.ff) in the list and the 1st element is ignored. If new IPs are added to the list the problem repeats. All the elements in the beginning are skipped only the last one is considered. Please help to correct the for loop so that it iterates over all the elements.

1 个答案:

答案 0 :(得分:0)

我没有要测试的服务器,所以让我剥离第二个for循环的内容。

问题在这里machine_new_ip="$(echo ${machine_info}|cut -d, -f2)"

这将在第一个for循环的每个循环中重写该变量,而不是为第二个for循环创建列表,而您仅以machine_new_ip变量结尾,该变量仅包含{{1}的最后一个元素}文件。

使用/home/priyashree/server.txt将创建一个列表,需要额外的空格来分隔值。

variable+=value

例如

for i in $(cat /home/priyashree/server.txt);do
     machine_ip=$(getent hosts $i | awk {'print $1'})
     machine_info="${i},${machine_ip}"
     machine_new_ip+=" $(echo ${machine_info}|cut -d, -f2)"
     #echo ${machine_new_ip}
done

for machineip in $machine_new_ip;do
        echo ${machineip}
done