Search code examples
shellshdash-shell

Validate an ip in dash (not bash)


I am trying to validate an ip address within a dash script. I've found many ways to achieve the same with bash such as in linuxjournal

Basically what is does is a comparision using this:

if [[ $ip =~ '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' ]]; then
  do something
fi

Is there any way to get the same with dash?

UPDATE: This is the final script that does what I needed:

#In case RANGE is a network range (cidr notation) it's splitted to every ip from 
# that range, otherwise we just keep the ip
if echo $RANGE | grep -E -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2}$'; then
    IPS=`prips $RANGE -e ...0,255`
    if [ "$?" != "0" ] ; then
        echo "ERROR: Not a valid network range!"
        exit 1
    fi
elif echo $RANGE | grep -E -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'; then
    IPS="$RANGE"
else
    echo "$RANGE no is not a valid IP address or network range"
    exit 1
fi

Solution

  • Assuming you are happy with the validation string:

    $ s='[0-9]\{1,3\}'
    $ echo $ip | grep > /dev/null "^$s\.$s\.$s\.$s$" &&
      echo $ip is valid
    

    Note that this accepts invalid ip addresses like 876.3.4.5

    To validate an ip, it's really not convenient to use a regular expression. A relative easy thing to do is:

    IFS=. read a b c d << EOF
    $ip
    EOF
    
    if ( for i in a b c d; do
            eval test \$$i -gt 0 && eval test \$$i -le 255 || exit 1
        done 2> /dev/null )
    then
        echo $ip is valid
    fi