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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…