bash - 默认返回的条件返回不起作用
问题描述
我有一个 bash 函数,它的作用是接收一个数组,遍历数组并调用另一个函数is_node
来检查节点元素是否存在。
如果节点元素存在 `is_node' 返回 0,如果出错则返回 1-6 之间的数字,否则返回 7 或以上。
我的问题is_nodes
是即使'is_node'return 0
会return 7
!return 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
}
伪码
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
解决方案
这是修复代码的尝试。
# 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
也可以降为just if [[ "$rc" -lt 7 ]]
。