1

I have this command:

ptr=`host $hostname`

Which results in this:

test.tester.test has address 192.168.1.1

This Works!

What I want now is to extract only the IP address (192.168.1.1), pass it to the variable $myptr and run the following command:

if $myptr | sed -n '/\(\(1\?[0-9][0-9]\?\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\(1\?[0-9][0-9]\?\|2[0-4][0-9]\|25[0-5]\)/p' ; then
   host $myptr
else
   echo "No PTR Record found"
fi

But it does not work. Please help?

4

You don't need any extravagant text processing on the output of host, you can just use dig +short to get only the IP address (and do the required reverse lookup on the IP).

dig +short "$hostname"

e.g.

ip="$(dig +short "$hostname")"
host "$ip"

Or directly:

host "$(dig +short "$hostname")"
  • Legend, Thank you... Chasing my own tail there... – user2720970 Sep 20 '16 at 5:58
0

To extract ip you can awk it for example:

ptr=`host $hostname | awk '/has address/ {print $NF}'`
  • /has address/ mach only line that has this string as host can return much more for you. Try google for example.
  • print $NF - NF is awk's variable returning number of fields, so $NF points to last field.

Then you could use grep and check it's return code (sed will return 0 regardles if it will find your regexp or not. So doing something like this would work:

echo $ptr | egrep "your pattern"
if [ $? -eq 0 ]; then
    echo "This Works"
fi

But you could simply check if $ptr contains an output. If host command won't find anything $ptr will be empty, so:

if [ -n $ptr ]; then
    echo "Works"
else 
    echo "Not found :("
fi

Take a look at man test:

-n STRING
          the length of STRING is nonzero
-z STRING
          the length of STRING is zero

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.