Tony
Tony

Reputation: 486

bash - if command output is NOT null, write output to a file

I feel like this should be very, very, easy... but somehow I can't figure it out.

The matter is simple. I have the following if statement, which I'm using to check IPs and see if they have a reverse DNS or not. If there is a valid Reverse DNS available, I write it to a file. If not, I write "NXDOMAIN" to the same file.

if [[ $(dig +noall +answer -x 10.10.10.10 | grep -m 1 PTR | awk '{ print $5 }') ]]; then
       dig +noall +answer -x 10.10.10.10 | grep -m 1 PTR | awk '{ print $5 }' > /root/IP
else
       echo "NXDOMAIN" > /root/IP
fi

This works OK, but it runs the command twice, unnecessarily. Is there a way in which, if the command returns a valid reverse DNS, I can output it directly to a file, without running the command again?

So, basically, something like this:

if [[ $(dig +noall +answer -x 10.10.10.10 | grep -m 1 PTR | awk '{ print $5 }') ]]; then
       <write output of the above command in the "/root/IP" file>
else
       echo "NXDOMAIN" > /root/IP
fi

Upvotes: 0

Views: 4926

Answers (2)

jkdba
jkdba

Reputation: 2519

Why not store it in a variable like so:

RevLookup="$(dig +noall +answer -x 10.10.10.10 | grep -m 1 PTR | awk '{ print $5 }')"
if [[ "$RevLookup" ]]; then
       echo "$RevLookup" >> /root/IP
else
       echo "NXDOMAIN" >> /root/IP
fi

Upvotes: 4

selalerer
selalerer

Reputation: 3934

Put the result in a variable.

REV_DNS=$(dig +noall +answer -x 10.10.10.10 | grep -m 1 PTR | awk '{ print $5 }')
if [[ $REV_DNS ]]
then
    echo "$REV_DNS" > /root/IP
else
    echo "NXDOMAIN" > /root/IP
fi

Upvotes: 1

Related Questions