Hi,

I trying to test two condition together (AND) under bash but it’s not working…

The goal is ti have True when two variables are either not set or empty (empty string)

I’ve tried

if [[ -n VARIABLE1 && -n VARIABLE2 ]]; then
    echo "OK"
fi

Here I get the “OK” no matter what .

Thanks.

  • Rick_C137@programming.devOP
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    8 hours ago

    Thank you all for yours input

    What finally did work

    if [[ -z VARIABLE1 && -z VARIABLE2 ]]; then
        echo "OK"
    fi
    

    If only Linux was using Python syntax that would be so much more intuitive…

    • suff@piefed.social
      link
      fedilink
      English
      arrow-up
      13
      ·
      edit-2
      1 day ago

      Explanation

      [ is an alias for the program test, so you can call man test for more info.
      && is bash syntax for conjunction. In A && B, B will only be called if A returned a exit code >0 (error). You can call man bash for more info.
      || is bash syntax for disjunction. In A || B, B will only be called if A returned exit code =0 (success). true and false are programs that just return exit codes 0 respectively 1.

  • kittenroar@beehaw.org
    link
    fedilink
    English
    arrow-up
    1
    ·
    23 hours ago

    You need to reference the value of the variable, ie:

    if [[ -n "$VARIABLE1" && -n "$VARIABLE2" ]]; then
        echo "OK"
    fi
    
      • kittenroar@beehaw.org
        link
        fedilink
        English
        arrow-up
        1
        ·
        edit-2
        14 minutes ago

        Then it is working. That is what that code was checking for.

        Specifically, -n checks if the variable exists and also does not have a null value.

        If you want to reverse it, ie, check that those conditions are not true, put an exclamation mark in front of the whole thing.

  • thingsiplay@beehaw.org
    link
    fedilink
    arrow-up
    1
    ·
    23 hours ago

    Try this:

    #!/usr/bin/env bash
    
    a=""
    if [[ -z "${a}" && -z "${b}" ]]; then
        echo "OK"
    else
        echo "Not OK"
    fi
    
    a="OK"
    if [[ -n "${a}" && -z "${b}" ]]; then
        echo "More ${a}"
    else
        echo "More Unokay"
    fi