How to get dig +short to return something when there is no answer?

Solution 1:

There is no real way to make +short do what you want it to in this context. It's simply the wrong tool for the job when working with bulk data.

The solution I found when running into this problem was to use a combination of filters: +noall +question +answer. +noall turns all display fields off, +question displays the query being made with a ; comment prefix, and +answer displays the answer.

The output looks like this:

$ dig +noall +question +answer google.com serverfault.com
;google.com.                    IN      A
google.com.             284     IN      A       74.125.137.101
google.com.             284     IN      A       74.125.137.138
google.com.             284     IN      A       74.125.137.102
google.com.             284     IN      A       74.125.137.100
google.com.             284     IN      A       74.125.137.113
google.com.             284     IN      A       74.125.137.139
;serverfault.com.               IN      A
serverfault.com.        187     IN      A       198.252.206.16

In the event that you get no response back, you will see two adjacent questions. You won't know why the query failed as this output doesn't display a RCODE (neither does +short), but the output is sufficient for analyzing a bulk data set and locating records that need more verbose analysis.

If you find yourself doing bulk analysis of DNS referrals, switch +answer out for +authority.

Solution 2:

Something like this is good for pasting as it will preserve exactly one line of output for every line of input in case there is either 1 or 0 responses (which the accepted answer does not). It prints either the IP or the original FQDN. If needed it can be altered to print all the resolved IPs within one line, but I knew in my case there is only one IP.

for i in $(cat list); do
   ip=$(dig +short $i)
   [ -z "$ip" ] && echo $i || echo $ip
done

It saves the answer to a variable and then checks if the variable is empty (not answer, print the input), or not empty (print the output).