有条件退货,默认退货不起作用

时间:2018-09-24 12:35:42

标签: bash

我有一个bash函数,其作用是接收一个数组,遍历该数组并调用另一个函数is_node,以检查是否存在节点元素。

如果节点元素存在,则“ is_node”返回0,如果抛出错误,则返回1-6之间的数字,否则返回7或更高。

我对is_nodes的问题是即使'is_node'return 0return 7

!返回7,如果没有错误出现并且不存在节点,则应触发

 function is_nodes() { 
    local arr=("$@")    

    for node in ${arr}
    do
        is_node $node 
        if [[  $? -gt 0 && $? -lt 7  ]]
        then
            return 2
        elif [[ $? -eq 0 ]]
        then
            return 0
        fi  
    done
    # default
    return 7
}

pesudeo代码

is_nodes receive an array (node1 node2 node3)
loop
  is_node node1 triggers an error ?; no go further
  is_node node1 exists(return 0) ?; no continue   
  is_node node2 triggers an error ?; no go further
  is_node node2 exists(return 0) ?; yes get out of the function and return 0

1 个答案:

答案 0 :(得分:2)

这是尝试修复您的代码。

# Don't use Bash-only keyword function
is_nodes() {
    # New variable
    local rc
    # No array needed, just loop over arguments
    for node in "$@"
    do
        # Take care to properly quote argument
        is_node "$node"
        # Capture result
        rc=$?
        if [[ "$rc" -gt 0 && "$rc" -lt 7  ]]
        then
            return 2
        elif [[ "$rc" -eq 0 ]]
        then
            return 0
        fi  
    done
    # default
    return 7
}

我的一部分想重构return 0,因此您无需将$?与零进行显式比较。

        is_node "$node" && return 0

,然后相应地取出elif分支。然后,if中的条件也可以减少为if [[ "$rc" -lt 7 ]]