bashif-statementconditional-statements

bash if-elif-else sequence get "conditional binary operator expected on first elif


learning / relearning bash scripting. The following if - elif statement gets a conditional binary operator error on the first elif:

if [  $len -eq 1 ]; then 
grep -i -H $1 *.org
elif [[ [ $len -eq 2 ] -a { [ $1 == "keyword" ] -o [ $1 == "todo" ] } ]]; then

Yeah, I am an old noob, I am stumped. it looks ok to me. swgeek

Corrected some spacing errors, tried playing with parenthesis, searched here on conditional binary operator, and will continue that search, but nothing close enough for the light bulb to go on.


Solution

  • All the extra bracketing inside [[ ... ]] is invalid. It should be

    elif [[ $len -eq 2 && ( $1 == "keyword" || $1 == "todo" ) ]]; then
    

    Inside double square brackets you use parentheses for grouping, not square brackets or curly braces. And it uses C-style logical operators.

    Or you can use standard single square brackets, but then you use && and || between the commands, not -a and -o (those are only used inside brackets). You also need ; before the closing }.

    elif [ $len -eq 2 ] && { [ "$1" = "keyword" ] || [ "$1" = "todo" ]; }; then
    

    Square brackets also allow using -a and -o between expressions inside a single set of brackets, but this is considered obsolete due to ambiguities with those operators, so it's preferable to use the conditional syntax above.