Array help

Hi all,

I have the scenario where i have different categories of servers of 4 pairs, like pairA=4 serves,pairB=4 servers like that. I want to store them in an array with their hostnames, depends on that hostname iam running this script if that falls in any array the script should do something.
I wrote a script which iterates each element in that array and check an if condition but if i include else statement it's not working.
Please take a look and correct and also if there's a better way to do it.

#!/usr/bin/bash
Array1=( HOST1 HOST2 HOST3 HOST4 )
HOSTNAME=`hostname`
for i in ${Array1[@]}
do
Array1[$i]=$i
if [[ "${Array1[$i]}" = $HOSTNAME ]]
then
echo "This is Type 1 server"
Do something here......just for this server and then should exit
fi
done
Then same for next pair of array....

I tried including else but it didn't exit but test for next value in that array which i dont want .

Please help me.

Thanks in advance.

Hi,

Please somebody reply me.

Let me know if you need more information.

Thanks.

In your loop, $i takes the value of each element of the array $Array1. But you are using it as an array index in Array1[$i]. Put an echo $i in the loop to see what it's doing. If you really need to loop over an array, do

Array1=( HOST1 HOST2 HOST3 HOST4 )
HOSTNAME=`hostname`
for i in $(seq 0 $((${#Array1[@]} - 1)))
do
  if [[ "${Array1[$i]}" = $HOSTNAME ]]
  then
    echo "This is Type 1 server"
  fi
done

But arrays in bash are ugly when you can just do

hosts="HOST1 HOST2 HOST3 HOST4"
HOSTNAME=`hostname`
for h in $hosts
do
  if [ "$h" = "$HOSTNAME" ]
  then
   ...
  fi
done


Thanks for your reply. I inserted echo $i and it displayed each elements of array1 in each line.
I would like to know if i declare 2 or 3 arrays with different set of hosts, within a single for loop will i be able to jump from array to array if the hostname not matches. so the script will now have multiple for loops.
Say if
Array1="HOST1 HOST2 HOST3 HOST4"
Array2="HOST5 HOST6 HOST7 HOST8"
Array3="HOST9 HOST10 HOST11 HOST12"
for should include all the elements(Array1+Array2+Array3) but the if loop should maches $HOSTNAME and each elements of Array1 and if not elif should try match for next Array2 and so on and let me know what array the hostname matches.
Also is it ok if i dont give any else condition in an if loop? if the if condition matches will it come out of the loop even if i didnt give any break statement?

Thanks.

Hi,

Please never mind,i figured it out myself.
Thanks spirtle for your reply.

Best Regards.