Reputation: 2952
I need to use cron and bash to check if IP 111.222.333.444 is still valid for host sub.domain.com.
I have tried grep with -Pzo, but it didn't work. I don't want to install pcregrep.
#!/bin/bash
ipaddressused=$1
#Run a dig for sub.domain.com:
ipaddresscurrent='dig +short sub.domain.com'
echo "$ipaddresscurrent" | grep -Pzo "$ipaddressused" && echo "found" && exit 0 || echo "not found" && exit 1
ipaddresscurrent returns multiple IPs, one per line.
How do I make this work?
Upvotes: 1
Views: 726
Reputation: 46903
Wouldn't this be enough?
#!/bin/bash
ipaddressused=$1
if grep -q -P "$ipaddressused" < <(dig +short sub.domain.com); then
echo "found"
exit 0
else
echo "not found"
exit 1
fi
What was wrong with your script?
The line
ipaddresscurrent='dig +short sub.domain.com'
assigns the string dig +short sub.domain.com
to the variable ipaddresscurrent
. You probably, instead, wanted to assign to the variable ipaddresscurrent
the output of the command dig +short sub.domain.com
. This is done either using the old and deprecated backticks:
ipaddresscurrent=`dig +short sub.domain.com`
(but please don't ever use backticks!) or the more modern, robust and nestable $(...)
as:
ipaddresscurrent=$(dig +short sub.domain.com)
grep -Pzo
doesn't really do what you're expecting. Instead you want to run grep
quiently (hence the -q
flag) and check its output, so the following would have been valid:
echo "$ipaddresscurrent" | grep -q -P "$ipaddressused" && echo "found" && exit 0 || echo "not found" && exit 1
Since you don't really need the variable ipaddresscurrent
, I prefered to use bash's process substitution to feed grep
.
Also, don't use long chains of && || &&
's, it's hard to read, and can have some subtle side effects.
If you want to stick with your variable, you need a here-string as so:
#!/bin/bash
ipaddressused=$1
ipaddresscurrent=$(dig +short sub.domain.com)
if grep -q -P "$ipaddressused" <<< "$ipaddresscurrent"; then
echo "found"
exit 0
else
echo "not found"
exit 1
fi
As you note in your comment:
should be noted that if the $ipaddressused supplied is 111.222.333.4 and 111.222.333.456 is present on the list a match will also occur. this could cause problems.
I actually didn't really know if this was a requested feature or not (since the argument of the script is a regex, that's actually why I left the -P
flag). If you really want to exactly match an IP, here's how you could proceed:
#!/bin/bash
if grep -q "^${1//./\.}$" < <(dig +short sub.domain.com); then
echo "found"
exit 0
else
echo "not found"
exit 1
fi
assuming that dig
used this way will output only one ip per line.
Upvotes: 2