将布尔表达式的结果存储到变量中 [英] Storing into variable a result of boolean expression

查看:47
本文介绍了将布尔表达式的结果存储到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将布尔表达式的结果连续存储到变量中?

Is it possible to continuously store a result of boolean expression into a variable?

示例

ret=0
for each in aCollection do
    executeSomeCommand;
    # vvv compare stored value against a returned value and store it again
    ret=$ret || $?;
done;
[[ ret = 0 ]] && echo "success"

问题在于,如果 $? 1 ,则 $ ret 仍包含零

The problem is that if $? is 1, then $ret still contains zero

ret=0
echo $ret # --> 0
ret=$ret || 1
echo $ret # --> 0 (should be 1)

推荐答案

您遇到分组/操作顺序问题.当你做

You have a grouping/order of operations problem. When you do

ret=$ret || 1

首先执行 ret = $ ret ,然后获取结果,然后对 1 进行 || ,然后忽略结果其中.因此,您要做的分配工作的唯一部分就是再次将 ret 分配给它自己.

it is first doing ret=$ret and then taking the result of that and doing an || with 1 then ignoring the result of that. So the only part of the assignment you're doing is assigning ret to itself again.

您想要做的是 $ ret ||1 部分并存储结果,因此您需要使用像

What you want is to do the $ret || 1 part and store the result, so you need parens like

ret=$(($ret || 1))

这篇关于将布尔表达式的结果存储到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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