28

I have a small piece of code which checks IP address validity :

function valid_ip()
{
    local  ip=$1
    local  stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        if [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]; then
            stat=1
        else
            stat=0
        fi
    fi
    return $stat
}

But I am having problems with its usage in bash conditionals. I have tried many techniques to test its return value but most of them fail on me.

if [[ !$(valid_ip $IP) ]]; then

if [[ $(valid_ip IP) -eq 1 ]]; then

etc. etc. Can anyone suggest what should I do here ?

EDIT

Following your suggestions I have used something like :

  if valid_ip "$IP" ; then
      ... do stuff
  else
      perr "IP: \"$IP\" is not a valid IP address"
  fi

and I get errors like

IP: "10.9.205.228" is not a valid IP address

2 Answers 2

27

The return code is available in the special parameter $? after the command exits. Typically, you only need to use it when you want to save its value before running another command:

valid_ip "$IP1"
status1=$?
valid_ip "$IP2"
if [ $status1 -eq 0 ] || [ $? -eq 0 ]; then

or if you need to distinguish between various non-zero statuses:

valid_ip "$IP"
case $? in
    1) echo valid_IP failed because of foo ;;
    2) echo valid_IP failed because of bar ;;
    0) echo Success ;;
esac

Otherwise, you let the various operators check it implicitly:

if valid_ip "$IP"; then
    echo "OK"
fi

valid_IP "$IP" && echo "OK"

Here is a simple, idiomatic way of writing valid_ip:

valid_ip () {
    local ip=$1
    [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && {
        IFS='.' read a b c d <<< "$ip"
        (( a < 255 && b < 255 && c < 255 && d << 255 ))
    }
}

There are two expressions, the [[...]] and the { ... }; the two are joined by &&. If the first fails, then valid_ip fails. If it suceeds, then the second expression (the compound statement) is evaluated. The read splits the string into four variables, and each is tested separately inside the arithmetic expression. If all are true, then the ((...)) succeeds, which means the && list succeeds, which means that valid_ip succeeds. No need to store or return explicit return codes.

Sign up to request clarification or add additional context in comments.

2 Comments

The shell interprets 0 as success and non-zero as failure, opposite of the usual Boolean interpretation. valid_IP should return 0 if the IP address is valid, and 1 otherwise.
No. That's a problem with set -e not with this.
19

No parentheses needed if the exit status is inspected:

if valid_ip $IP ; then
    ...

Just call the function in the way you would call any other command.

3 Comments

@Patryk: Note that commands return 0 on success. Return 0 for a valid IP.
But I thought ${ip[0]} -le 255 is to check that first octet is less than or equal to 255 and so on for remaining octets.
@Patryk: No problem with that. Just switch stat=0 and stat=1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.