如何遍历列表,而忽略列表中的某些元素?

时间:2018-11-14 07:30:20

标签: bash shell

我有两个列表,我的脚本在其中循环。我只想使用列表中的VM,而忽略主机。列表的大小和顺序可能非常好,所以我不能使用索引。我该怎么办?

目前,我正在遍历所有元素,这是不希望的,因为HOSTS不在主机文件中,而在DNS中。

production=(VM01 VM02 VM03 HOST01 HOST02)
staging=(VM04 VM05 VM06 HOST03 HOST04)
for host in ${production[@]} ${staging[@]}
  do
    if [[ ! `grep $host /etc/hosts` ]]
      then
        echo "$host is not in /etc/hosts file. Exiting."
        exit
    fi
  done

2 个答案:

答案 0 :(得分:1)

只需检查要跳过的字符串匹配项即可:

if [[ $host =~ HOST* ]]; then continue; fi

在循环的顶部。

答案 1 :(得分:0)

测试字符串是否包含为:

if [[ $host == *VM* ]]

这是您的完整测试:

#!/bin/bash

production=(VM01 VM02 VM03 HOST01 HOST02)
staging=(VM04 VM05 VM06 HOST03 HOST04)
for host in ${production[@]} ${staging[@]}
do
    if [[ $host == *VM*  ]]; then
        echo "${host} contains VM";
    else 
        echo "${host} doesn't contain VM";
    fi
done

输出将是:

VM01 contains VM
VM02 contains VM
VM03 contains VM
HOST01 doesn't contain VM
HOST02 doesn't contain VM
VM04 contains VM
VM05 contains VM
VM06 contains VM
HOST03 doesn't contain VM
HOST04 doesn't contain VM