Search code examples
bashdo-while

do while true case with only the given character


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

Solution

  • 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).