mickt
mickt

Reputation: 57

How can I loop through a list, ignoring some elements in the list?

I have two lists, which my script loops through. I want to use only the VMs in the lists and ignore the hosts. The list size and order may very so I can't use indexes. I How might I do this?

Currently I am looping through all elements, which is not desired as HOSTS are not in hosts file as they are in 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

Upvotes: 2

Views: 752

Answers (2)

Hearen
Hearen

Reputation: 7838

Testing string whether contains as:

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

Here is your complete test:

#!/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

output will be:

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

Upvotes: 0

kabanus
kabanus

Reputation: 25980

Just check for a string match to skip:

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

at the top of the loop.

Upvotes: 1

Related Questions