user3700919
user3700919

Reputation: 375

How can I use two arrays to check if DNS records exists in Bash?

I want to check if the following records exist with two arrays. I'm not sure if this is the best way of going about it, but from the logic it looks like it may be possible from the code below:

Domain_checking () {
    array=(
        grafana
        kibana
        prometheus
        alertmanager
    )

    array2=(
        Name
        NXDOMIAN
    )


    for index in ${!array[*]}; do 
        echo "checking that ${array[$index]} exists in the domain domain.co.uk"
        DOMAIN_CHECK=$(nslookup ${array[$index]}.domain.co.uk | grep {array2[$index]})
        if [[ $DOMAIN_CHECK == *'Name'* ]]; then
            echo "The A record for ${array[$index]}.domain.co.uk exists"
        elif [[ $DOMAIN_CHECK == *'NXDOMIAN'* ]]; then 
            echo "The A record for ${array[$index]}.domain.co.uk dose not exist"
        fi
    done
}

Domain_checking

When the code above is run, the loop does start and for the echo statement, I see the values in both arrays when I add {array2[$index]} to the echo statement.

But the array values are not present in DOMAIN_CHECK, which I'm not sure as to why this is as the for loop does iterate.

So I would expect that DOMAIN_CHECK should have some sort of value and hit the if statement but for some reason, this doesn't seem to be the case. Why is that?

Upvotes: 1

Views: 1737

Answers (2)

arco444
arco444

Reputation: 22861

It appears you're only using nslookup to see if the domain exists or not, rather than looking for specific information from the command. You can simplify by just checking the exit code instead of using grep:

Domain_checking () {
    array=(
        grafana
        kibana
        prometheus
        alertmanager
    )

    for domain in ${array[@]}
    do
      if nslookup "${domain}.domain.co.uk" >/dev/null 2>&1 ; then
        echo "$domain exists"
      else
        echo "$domain does not exist"
      fi
    done
}

Domain_checking

If the domain record exists, nslookup will return 0 and the if condition will be satisfied. Anything else indicates a failure and the control will fall through to the else.

Upvotes: 2

erik258
erik258

Reputation: 16304

You use $index as an index to both arrays, but there's a matching entry in $array2 only for the first entry. That's why the other entries aren't showing up, and also why grep is missing it's required argument.

Thinking through your logic, I don't see any reason not to remove the second array completely and hard code in Name for the grep.

Come think of it, the first array isn't helping much either. You could simplify the code by iterating across the names themselves rather than their array indices.

domain=some.thing
names="kibana prometheus graphite"
for name in $names; do
   nslookup $name.$domain ....
done

Upvotes: 2

Related Questions