【发布时间】:2013-12-26 22:00:07
【问题描述】:
下面的程序应该读取并验证用户键入的 IP 地址。 IP 验证工作正常。我需要弄清楚设置条件(while/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
【问题讨论】:
-
为什么要重新设计轮子?使用
ipcalc。此工具在成功时返回 0,在失败时返回 1。因此ipcalc -s -c <ip>如果 ip 有效则返回 0,如果无效则返回 1。作为旁注:有两个if,但只有一个fi。
标签: linux bash shell scripting