Monday, 6 October 2014

Shell Script : How to use an array to get n number of similar set for different values

In this example we are going to obtain below set (used in nagios config to define a host) using array -

define host{
              use                     linux-server
              host_name              <host>
              alias                        <host>
              address                    <ip>
            }

I have two files, one contains hostname  and second has their IPs.

host.txt           ip.txt 
host1               x.1
host2               x.2
host3               x.3
host4               x.4


Code :

#!/bin/bash

#### Storing the host names in array 'arr', reading from host.txt


j=1
for i in `cat host.txt`
do
  arr[$j]=$i

  j=`expr $j + 1`

done

#### Storing the IP's names in array 'arrp', reading from ip.txt


k=1

for m in `cat ip.txt`
do
  arrp[$k]=$m

  k=`expr $k + 1`

done

#### Taking count of the records


count=`cat host | wc -l`


#### Printing the values stored in the two arrays for making the set


for x in `seq 1 $count`

do
echo "define host{
              use                     linux-server
               host_name           ${arr[$x]}
              alias                      ${arr[$x]}
              address                 ${arrp[$x]}
            }"  
done
##############

Output : 

define host{
              use                     linux-server
               host_name        host1
              alias                   host1
              address              x.1
            }
define host{
              use                     linux-server
               host_name        host2
              alias                   host2
              address               x.2
            }
define host{
              use                     linux-server
               host_name         host3
              alias                    host3
              address                x.3
            }
define host{
              use                     linux-server
               host_name          host4
              alias                     host4
              address                x.4
            }



 Like above we can use array to make similar n number of sets for different values instead of  writing multiple times :)  

No comments:

Post a Comment