do while true case with only the given character

108 Views Asked by At

I need a script which adds some information to my server after starting the script. It needs to input the IP address but I also want it to send me an error message if I did not input the IP in the correct form.

What I tried:

while true ; do
   read -p "which IP did the Location used? in this form xx.xx.xx" newip
   case $newip in
       [0123456789.]* )echo "success";break;;
       * ) echo "only input in this Form xx.xx.xx";;
   esac
done

What I wanted:

which IP did the Location use? in this form xx.xx.xx
input: 10.10.10
output: success

which IP did the Location use? in this form xx.xx.xx
input: 10-10.10
output: only input in this Form xx.xx.xx

which IP did the Location use? in this form xx.xx.xx
input: 10.10.10
output: success
2

There are 2 best solutions below

0
tripleee On BEST ANSWER

If you want to stick to case, you can exclude the parts which are wrong, to focus on those which are correct.

while true ; do
   read -p "Which IP did the location use? In this form xx.xx.xx.xx " newip
   case $newip in
       *[^0-9.]* | *.*.*.*.* ) ;;
       *.*.*.* ) echo "success"; break ;;
       * ) ;;
   esac
   echo "only input in this Form xx.xx.xx.xx" >&2
done

Real IP addresses have four octets; if you genuinely want only three, it should hopefully be obvious how to change this.

Perhaps also notice the addition of a space at the end of the read -p prompt (as well as some minor English fixes).

0
jhnc On

In a glob, * matches any character.

Bash does have regex support using =~. For example:

if [[ $newip =~ ^[0-9]{2}\.[0-9]{2}\.[0-9]{2}$ ]]; then
    echo ok
else
    echo bad
fi