Shell script to read an IP address from user\'s input and check if the input IP
ID: 3741142 • Letter: S
Question
Shell script to read an IP address from user's input and check if the input IP address is valid or not.
Fill in the Blank to complete the task!
#!/bin/bash
echo -n "Please enter the ip:"
_______A._______
echo $ip|grep _______B.______________
if [_______C._______]
then
echo "Please enter IP address following the
IP address pattern"
exit
fi
#replace the dots in ip with spaces
ip=`echo $ip | sed _______D._______
valid=1
n=1
for num in $ip
do
if [ _______E._______ ]
then
echo "INVALID: Please enter a number
between 0-255 in field $n (index starts
from 1 from left)"
valid=0
exit
fi
n=`expr $n + 1`
done
if [ $valid -eq 1 ];then
echo "The ip you entered is valid"
fi
Explanation / Answer
#!/bin/bash
echo -n "Please enter the ip: "
read ip
# check if IP follows the correct pattern
echo $ip | grep '^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$'
if [ $ip -ne ]
then
echo "Please enter IP address following the
IP address pattern"
exit
fi
#replace the dots in ip with spaces
ip=`echo $ip | sed "s/./ /g"`
valid=1
n=1
for num in $ip
do
if [ $num > 255 -o $num < 0 ]
then
echo "INVALID: Please enter a number
between 0-255 in field $n (index starts
from 1 from left)"
valid=0
exit
fi
n=`expr $n + 1`
done
if [ $valid -eq 1 ];then
echo "The ip you entered is valid"
fi
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.