1
我想做兩件事:1.測試IP地址的有效性。 2.在具有多個IP地址的文件中搜索IP地址。 「ips」是文件。這是我迄今爲止所擁有的。每次運行腳本時,我都會得到這個結果:如果IP地址在文件中,我總是會得到「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 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
你是'while'塊內創建一個功能? – fedorqui
我是新來的,所以如果我做得不對,我會很感激任何建議。謝謝fedorqui –
首先,將函數聲明移到'while true'行之上,並且在函數中,將參數指向$ 1而不是$ ip。另外你在if語句中缺少一個正方括號。 – rojomoke