Reputation: 585
I am trying to do two things: 1. Test ip address for validity. 2. search the ip address in a file with many ip address. "ips" is the file. This is what I have so far. Every time I run the script I get this: It does not matter if the ip address is in the file I always get "IP address NOT found, and saved". Please help. Thank you in advanced
$ ./test1
IP address: 202
Not Valid. Please re-enter the ip address
IP address: 202.124.64.0
IP address NOT found, and saved
IP address: 109.234..232.0
Not Valid. Please re-enter the ip address
IP address: 109.234.232.0
IP address NOT found, and saved
The script:
#!/bin/bash
while true; do
echo -e "IP address: \c"
read ip
function valid_ip()
{
local stat=1
if [[ $ip =~ [0-9]{1,3}\.[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 \
&& ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
if valid_ip $ip; then
if grep 'valid_ip $ip' ips; then
echo "IP address found, and saved"
else
echo "IP address NOT found, and saved"
fi
else
echo "Not Valid. Please re-enter the ip address"
fi
done
Upvotes: 1
Views: 121
Reputation: 11633
Your quoting is off. $
variables don't expand in single quotes in bash, so it's searching for the string $ip
, not the ip address contained in the variable. So
if grep 'valid_ip $ip' ips; then
should be
if grep $(valid_ip "$ip") ips; then
Upvotes: 1
Reputation: 786146
Keep your function like this:
valid_ip() {
local stat=1
ip="$1"
if [[ $ip =~ [0-9]{1,3}\.[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
a=($ip)
IFS=$OIFS
[[ ${a[0]} -le 255 && ${a[1]} -le 255 && ${a[2]} -le 255 && ${a[3]} -le 255 ]]
stat=$?
fi
return $stat
}
Then call it as:
while true; do
reap -p "Enter an IP address: " ip
if valid_ip $ip; then
echo "IP address found, and valid"
break;
else
echo "Not Valid. Please re-enter the ip address"
fi
done
Upvotes: 1