Search code examples
bashxorlogical-operators

Compound if / logical XOR bash bug?


#!/bin/bash

function logic_test()
{
    left_bracket=$1
    right_bracket=$2

    if [[ ($left_bracket || $right_bracket) && ! ($left_bracket && $right_bracket) ]]
    then
        errEcho "Input error: insertIntoConfigFile arg1 does not contain matching []."
    else
        errEcho "Passed"
    fi
}

logic_test true true
logic_test true false
logic_test false true
logic_test false false

Expected results, as per XOR's functioning:

Passed
Input Error
Input Error
Passed

Actual results in 4.3.11(1)-release

Passed
Passed
Passed
Passed

Am I failing to see something trivial in my XOR implementation, or is the if logic buggy? If it is a bug, how do I go about submitting said bug?

I'm thinking this might be a bug...if I change the if to

if [[ ($left_bracket && !$right_bracket) || (!$left_bracket && $right_bracket) ]]

then all 4 outputs become "input error"


Solution

  • You can use set -xv to turn on debugging. It will show you the problem: bash interprets the things in [[ .. ]] as strings and tests them with -n. None of them is emtpy, so it works as 'true true' everytime.

    To fix it, just remove the [[ and ]]. Bash will correctly interpret true and false as commands to run and use their exit code in the logic.