0

I am converting my script from bash to dash... and have problem getting the return code of a function.

#!/bin/sh
check_ip() {
    local netbit=`echo "$1" | awk -F\/ '{print $1}'`
    local netmask=`echo "$1" | awk -F\/ '{print $2}'`

    if case "$netbit" in
        *[!.0-9]* | *.*.*.*.* | *..* | [!0-9]* | *[!0-9] ) false ;;
        *25[6-9]* | *2[6-9][0-9]* | *[3-9][0-9][0-9]* | *[0-9][0-9][0-9][0-9]* ) false;;
        *.*.*.* ) true ;;
        * ) false ;;
    esac; then
        if [ ! -z "$netmask" ] ; then
            if [ "$netmask" -ge 1 ] && [ "$netmask" -le 32 ] ; then
                return 0
            else
                return 1
            fi
        else
            return 0
        fi
    else
        return 1
    fi
}

# this is working without the [] thing.
if check_ip "$1" ; then
    echo ok
else
    echo no
fi

looked up the similar script from another machine, and it has no [] as @barmar suggested. all working now. thank you very much.

4

2 回答 2

2

$? reads the exit status of the last command executed.

a() {
  return 0;
}

b() {
  return 1;
}

a;
echo $?;
b;
echo $?;

would return:

0
1
于 2013-06-21T05:13:27.800 回答
0

The if command chooses the then or else clauses based on the exit status of the command. You only use [ if you want to perform the tests defined in the test command; if you just want to test a specific command, you use it directly.

if check_ip "$ip"
then echo Good IP
else echo Bad IP
fi

It's also very unlikely that $! would be an appropriate parameter to your function. $! is the PID of the last background process that was started, not an IP.

于 2013-06-21T05:22:56.270 回答