Hi all,
I'm writing a bash script that executes a few perl scripts. One of the perl scripts that I need to execute requires two arguments with it.
The arguments are stored in a txt file, each line contains a hostname and its corresponding IP address separated by a ":" (colon), the txt file looks like this below:
---hosts.txt---
host123PHI:192.168.1.0
host456ATL:192.168.1.1
host789BAL:192.168.1.2
host111BIS:192.168.1.3
host212CAL:192.168.1.4
more hosts etc.....
I'm not sure if it's the best way to accomplish this but here it goes.
In the bash file, let's call it
getHosts.sh, I create an array and assign each line of the file to an element in that array. I then think I need to create a new array where I take the hostname (which is before the ":") separate it from its IP address and place the IP address on a new line just below the hostname (this way I can reference to it like $hostNames[$x] would be the hostname, and $hostNames[$x+1] would be its IP address). So the new array would now look like this below:
host123PHI
192.168.1.0
host456ATL
192.168.1.1
host789BAL
192.168.1.2
host111BIS
192.168.1.3
host212CAL
192.168.1.4
more hosts etc.....
If there is a better way to attack this please let me know, as I am a beginner to bash shell scripting.
Here is what I have so far:
Code:
#This portion of code takes the INFILE and assigns each line to an element in the array
INFILE=/dir/location/hosts.txt
# Declare array
declare -a hostNames
# Link filedescriptor 10 with stdin
exec 10<&0
# stdin replaced with a file
exec < $INFILE
let count=0
while read LINE; do
hostNames[$count]=$LINE
((count++))
done
The code portion above works, but now I would like to separate each element on the ":" and push the second part of the element (IP address) to a new line/element. I was able to do that using the code below, but I am not able to make reference to an individual element.
Code:
for nameAddr in ${hostNames[@]};
do
echo $nameAddr
done
The resulting output of this portion of code above is what I want.
So how can I do this so I can use a for loop that would work like this:
Code:
for (( i=0; i < ${#hostNames[@]} ; i++ ));
do
./myCommandToRun.pl $hostNames[$i] $hostNames[$i+1]
done
If there is a better way for me to go at this please let me know. Any help would be greatly appreciated. Details and explanations of replies would be best as I am trying to learn.
Thanks in advance,
Matt
P.S. Sorry for the LONGG question, just trying to give as much detail as possible.