Reputation: 118
Is there an elegant way to compare exit codes of two functions in bash? For example
b ()
{
local r=$(rand -M 2 -s $(( $(date +%s) + $1 )) );
echo "b$1=$r";
return $r;
} # just random boolean
b1 () { b 1; return $?; } # some boolean function
b2 () { b 2; return $?; } # another boolean function ( another seed )
I'd like to use something like this
if b1 == b2 ; then echo 'then'; else echo 'else'; fi
but stuck with this "not xor" implementation
if ! b1 && ! b2 || ( b1 && b2 ) ; then echo 'then'; else echo 'else'; fi
And speaking more generally, can one compare exit codes of two functions arithmetically and use that comparison in if statement?
Upvotes: 1
Views: 1756
Reputation: 113834
To compare exit codes of b1
and b2
:
b1; code1=$?
b2; code2=$?
[ "$code1" -eq "$code2" ] && echo "exit codes are equal"
In shell, statements like b1 == b2
cannot stand alone. They need to be part of a test
command. The test
command is commonly written as [...]
.
Also, in shell, =
(or, where supported, ==
) are for string comparison. -eq
is for numeric comparison.
Upvotes: 1