Peter Uhnak
Peter Uhnak

Reputation: 10217

Storing into variable a result of boolean expression

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

Example

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"

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)

Upvotes: 2

Views: 566

Answers (1)

Eric Renouf
Eric Renouf

Reputation: 14510

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

ret=$ret || 1

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.

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

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

Upvotes: 5

Related Questions