Reputation: 3
I'm attempting to grep IPs from a number of files, look them up in DNS and compare them to the hostnames already in the same files to ensure both are correct. Then print out anything that is wrong.
I've gathered I need to put the information into arrays and diff them somehow.
Here is my horrible bash code which does not work. I'm pretty sure at least my for loop is wrong:
declare -a ipaddr=(`grep -h address *test.com.cfg | awk '{print $2}'`)
declare -a host_names=(`grep -h address *test.com.cfg | awk '{print $2}'`)
for i in "${ipaddr[@]}"
do
lookedup_host_names=( $(/usr/sbin/host ${ipaddr[@]} | awk '{print $5}' | cut -d. -f1-4 | tr '[:upper:]' '[:lower:]'))
done
if [[ -z diff <(printf "%s\n" "${lookedup_host_names[@]}"| sort ) <(printf "%s\n" "${host_names[@]}"| sort) ]]
then
printf "%s\n" "${lookedup_host_names[@]}"
fi
Upvotes: 0
Views: 166
Reputation: 123600
The two principal problems are that your for loop overwrites the array each time rather than appending, and your diff check is invalid.
To quickly fix the for loop, you could use +=
instead of =
, .e.g lookedup_host_names+=( ... )
.
To do the diff, you don't really need a condition. You could just run
diff <(printf "%s\n" "${host_names[@]}"| sort ) <(printf "%s\n" "${lookedup_host_names[@]}"| sort)
and it would show any differences between the two in diff format which most Unix users are familiar with (note that I switched the arguments around, since the first argument is supposed to be original).
If, like in your example, you actually do want to compare them and show the entire final list if there is a difference, you could do
if diff <(printf "%s\n" "${host_names[@]}"| sort ) <(printf "%s\n" "${lookedup_host_names[@]}"| sort) > /dev/null
then
printf "%s\n" "${lookedup_host_names[@]}"
fi
Upvotes: 0
Reputation: 2081
I don't see a difference between your arrays ipaddr and host_names. Supposed your files contain lines like
address 1.2.3.4 somehost.tld
a script like this may do what you want.
cat *test.com.cfg | grep address | while read line; do
IP=$(awk {'print $2'});
CO=$(awk {'print $3'});
CN=$(host $CO | cut -d ' ' -f 4)
[ "$CN" = "$IP" ] || echo "Error with IP $IP";
done
Upvotes: 1