#!/bin/bash
# valid ip
function isValidIp() {
local ip=$1
local ret=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
ip=(${ip//\./ }) # 按.分割,转成数组,方便下面的判断
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
ret=$?
fi
return $ret
}
# get target ip
function getTargetIp() {
targetIp="127.0.0.1"
while :
do
read -p "Please input target ip:" ip
if [ ! $ip ]; then
break # ip为空,说明没有输入,使用默认ip
fi
if isValidIp $ip; then
targetIp=$ip
break
else
echo "$ip is not a valid ip, please retry."
fi
done
}
getTargetIp
echo "Target ip is $targetIp"