我的要求如下,
if cond1 is true; then
if [[ val1 -lt val2 ]]; then
call_x_func
call_y_func
call_z_func
fi
else
if [[ val1 != val2 ]]; then
call_x_func
call_y_func
call_z_func
fi
fi
从上面可以看到,如果cond1为true,则使用运算符-lt或否则使用!=。循环内的内容保持不变。为了达到这个目的,我尝试在下面进行操作,但无法将bool值分配给bash变量。最好的方法是什么?
need_change=false
if cond1; then
need_change=[[ val1 -lt val2 ]]
else
need_change=[[ val1 != val2 ]]
fi
if $need_change; then
call_x_func
call_y_func
call_z_func
fi
我经常使用“ true”和“ false”,因为它们也是仅分别返回成功和失败的命令。那你可以做
cond1=false
if "$cond1"; then ...fi
您在这里寻找的内容:
need_change=false
cond1=true
if "$cond1"; then
if [[ val1 -lt val2 ]]; then need_change="true"; else need_change="false"; fi
else
if [[ val1 -ne val2 ]]; then need_change="true"; else need_change="false"; fi
fi
if "$need_change"; then
.
.
fi
由于bash没有bool数据类型,我建议您通过将数字值0解释为true,将其他任何值解释为false来对布尔模型进行建模。这样,您可以轻松地将程序的退出代码用作布尔值。例如:
need_change=1 # set to false
((val1 < val2)) # Test the values
need_change=$? # Set to true or false, according to the outcome of the test
# or:
need_change=$((val1 < val2)) # Alternative way to achieve this result.