1

That's how I try to do it.

read -p "enter ip " ip 
if [[ $ip =~ ^[1-255].[1-255].[1-255].[1-255]$ ]]; then echo "good"; fi

Only work if the input is 1.1.1.1

0

1 Answer 1

2

[1-255] means 1 or 2 or 5 , it won't match 1 to 255

use this instead, here I am counting occurrences

echo $ip | egrep -o '^([0-9]{1,3}\.){3}[0-9]{1,3}$'

[0-9]{1,3}\. means digit 0-9 can comes three times followed by dot

([0-9]{1,3}\.){1,3} means above pattern has to be three times

and yup , it will match incorrect IPs too.

2
  • Thank you it works perfectly and thank you for the explanation.
    – saad
    Jun 25, 2018 at 10:48
  • 1
    Note this regexp allow for IP like 345.456.567.678 have a look at dupplicate.
    – Archemar
    Jun 25, 2018 at 11:20

Not the answer you're looking for? Browse other questions tagged .