Use bash comparison result in another comparison

I would like to use the result of the comparison in a subsequent comparison. I am trying to do something like:

# $1 - expected result
# $2 - actual result
function print_result() {
    if [[ [[ $1 -eq 0 ]] -eq [[ $2 -eq 0 ]] ]]; then  # invalid
        echo "Pass"
    else
        echo "Fail"
    fi
}

I can get the desired behavior with a more detailed form:

function print_result() {
    if [[ (($1 -eq 0) && ($2 -eq 0)) || (($1 -ne 0) && ($2 -ne 0)) ]]; then 
        echo "Pass"
    else
        echo "Fail"
    fi
}

but it seems like there should be an easier way?

+4
source share
2 answers

You need something that gives the result of the comparison operator as text, and not as a return status. This will be the arithmetic expansion : $((expression)).

Note that bash contains a numerical expression, a conditional compound expression - (( expr ))- which is often easier to use for numerical comparisons than a non-numerical expression [[ ... ]]conditional compound.

Combining this, you are looking for:

if (( $(($1==0)) == $(($2==0)) )); then

:

if (( ($1==0) == ($2==0) )); then

, $1 $2 , , boolean not (!) 0, 1. , ( . ):

if ((!$1 == !$2)); then 

: script, , !, ( : , - .)

+2

, ( ) , , :

function print_result() {
    [[ $1 -eq 0 ]]; arg_one_is_zero=$?
    [[ $2 -eq 0 ]]; arg_two_is_zero=$?
    if [[ $arg_one_is_zero -eq $arg_two_is_zero ]]; then
        echo "Pass"
    else
        echo "Fail"
    fi
}

( ) , .

+1

All Articles