Bash 验证和搜索ip地址
我试着做两件事:1。测试ip地址的有效性。2.在具有多个ip地址的文件中搜索ip地址。“ips”是文件。这就是我目前所拥有的。每次运行脚本时,我都会得到这样的结果:不管文件中是否有ip地址,我总是会得到“ip地址未找到,并已保存”。请帮忙。提前谢谢你Bash 验证和搜索ip地址,bash,Bash,我试着做两件事:1。测试ip地址的有效性。2.在具有多个ip地址的文件中搜索ip地址。“ips”是文件。这就是我目前所拥有的。每次运行脚本时,我都会得到这样的结果:不管文件中是否有ip地址,我总是会得到“ip地址未找到,并已保存”。请帮忙。提前谢谢你 $ ./test1 IP address: 202 Not Valid. Please re-enter the ip address IP address: 202.124.64.0 IP address NOT found, and s
$ ./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
剧本:
#!/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
保持您的功能如下:
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
}
然后称之为:
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
你的报价被取消了
$
变量在bash中不以单引号展开,因此它搜索的是字符串$ip
,而不是变量中包含的ip地址。所以
if grep 'valid_ip $ip' ips; then
应该是
if grep $(valid_ip "$ip") ips; then
您是否在
while
块中创建函数?我是这方面的新手,因此如果我做得不对,我将非常感谢您的建议。感谢您fedorquiTo首先,将函数声明移到while true
行上方,并在函数中将参数引用为$1,而不是$ip。另外,if语句中缺少一个右方括号。