以下程序应该读取并验证用户输入的IP地址,对于IP的验证,它工作正常。我需要的是找出条件的设置(而/ if& else)会在输入无效的IP地址时提示用户重新输入IP?
echo "Enter an IP address:"
read IP_ADDRESS
# Check if the format looks right
if echo "$IP_ADDRESS" | egrep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
then
#check that each octect is less than or equal to 255:
VALID_IP_ADDRESS="$(echo $IP_ADDRESS | awk -F'.' '$1 <=255 && $2 <= 255 && $3 <=
25&& $4 <= 255')"
## Here is the Pseudo code of what I am trying to achieve
# If the IP address is not VALID_IP_ADDRESS prompt the user to re-enter IP
#Pseudo Code not actaul
while [[ ! VALID_IP_ADDRESS]] do
read -p "Not an IP. Re-enter: " IP_ADDRESS
done
# Another way to I tried
if $VALID_IP_ADDRESS; then
echo "You have alright IP address!"
else
read -p "Not an IP. Re-enter: " IP_ADDRESS
fi
答案 0 :(得分:1)
is_valid() {
IP_ADDRESS="$1"
# Check if the format looks right_
echo "$IP_ADDRESS" | egrep -qE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' || return 1
#check that each octect is less than or equal to 255:
echo $IP_ADDRESS | awk -F'.' '$1 <=255 && $2 <= 255 && $3 <=255 && $4 <= 255 {print "Y" } ' | grep -q Y || return 1
return 0
}
read -p "Enter a valid IP: " IP_ADDRESS
while ! is_valid "$IP_ADDRESS"
do
read -p "Not an IP. Re-enter: " IP_ADDRESS
done
echo "Success. You entered a valid IP address of $IP_ADDRESS"
答案 1 :(得分:0)
您错过了done
来关闭while [[ ! VALID_IP_ADDRESS]] do
。尝试添加它,看看您当前的解决方案是否有效。你也没有在循环中重新检查重新输入的ip。