Chris
Chris

Reputation: 159

Return value of function in IF statement shows strange behaviour

Can anyone explain what is going on here?

Why does an "IF" statement think the return is '1' (not Null) when i say 'Return 0' and the other way round.

I found that out while coding another script, so i developed this small script to test it:

#!/bin/bash

function testreturnzero()
{
        echo $1
        return 0
}


function testreturnone()
{
        echo $1
        return 1
}


if (testreturnzero 1) || (testreturnzero 2)
then
        echo "zero returned '1'"
fi


if (testreturnone 1) || (testreturnone 2)
then
        echo "one returned '1'"
fi

The IF which refers to the 'return 0' thinks its true (and doesn't process the second function), the IF which refers to 'return 1' thinks its false. Shouldn't it be the exact opposite?

1
zero returned '1'
1
2

I cant put the return value in a variable as I will have several of those checks.

Upvotes: 1

Views: 67

Answers (2)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

In bash, a function returning 0 means success and returning a non-zero value means failure. Hence your testreturnzero succeeds and your testreturnone fails.

Does that help understanding why your ifs behave that way? (it should!).

The return code of the last executed command/function is stored in the special variable $?.

So:

testreturnzero 0
ret_testreturnzero=$?
testreturnone 1
ret_testreturnone=$?
echo "$ret_testreturnzero"
echo "$ret_testreturnone"

will output (the two last lines):

0
1

Now you may think of storing them in a variable (as here) and do your logic processing later. But there's a catch :). Because you didn't store true and false in variables, you stored 0 and 1 (bash can't store booleans in a variable). So to check success or failure later:

if ((ret_testreturnzero==0)); then
    echo "testreturnzero succeeded"
fi

or

if ((ret_testreturnzero!=0)); then
    echo "testreturnzero failed"
fi

Upvotes: 2

naab
naab

Reputation: 1140

In bash, the return code of a function is the same as a external program when you test the result.

So for test, a valid return code is 0 and an invalid is any other number

so, by doing

if ( testreturnone 1 ); then #it is ok
   echo "error"; #it's supposed to happen, not an error
fi

You can explicitly test the value to the one you want to clear it up:

if [[ "$(testreturnzero 1)" = "1"); then #it is ok if you decide that 1 is the good value
   echo "ok";                            #But absolutly not the bash philosophy
fi

Upvotes: 2

Related Questions