如何在条件下使用 bash 返回码? [英] How to use bash return code in conditional?

查看:23
本文介绍了如何在条件下使用 bash 返回码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一小段代码可以检查 IP 地址的有效性:

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
}

但我在 bash 条件句中使用它时遇到问题.我尝试了许多技术来测试它的返回值,但大多数都失败了.

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 ?

编辑

根据您的建议,我使用了类似的东西:

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

我收到类似

IP:10.9.205.228"不是有效的 IP 地址

IP: "10.9.205.228" is not a valid IP address

推荐答案

返回码在命令退出后的特殊参数$?中可用.通常,您只需要在运行另一个命令之前保存它的值时使用它:

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"

<小时>

这是一个简单、惯用的 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 ))
    }
}

有两个表达式,[[...]]{ ... };两者由 && 连接.如果第一个失败,则 valid_ip 失败.如果成功,则计算第二个表达式(复合语句).read 将字符串拆分为四个变量,每个变量在算术表达式中分别进行测试.如果都为真,则((...))成功,即&&列表成功,即valid_ip 成功.无需存储或返回显式返回码.

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.

这篇关于如何在条件下使用 bash 返回码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆