Search code examples
bashshellscriptingbooleansh

Why does `if [false]` evaluate to true but `if false` doesn't in bash?


Running this script in bash will print "hello"

if [ false ]; then
    echo hello
fi

Running this script in bash will print "hello"

if [[ false ]]; then
    echo hello
fi

Only when I take away the brackets, bash will not print "hello"

if false; then
    echo hello
fi

I thought the entire premise of the brackets was to enable additional functionality like && and ||, why is it being counter-productive in this case?

edit: is this what you mean by bash quoting? still prints "hello"

test=false
if [[ "$test" ]]; then
    echo hello
fi

Solution

  • if function_or_program; then
        # do something
    fi
    

    This checks if function_or_program exits with 0 and if it does, executes the do something block.

    • true and false are functions (and programs) that exit with 0 and 1 respectively.

    • [ is a function (and a program, linked to test) that can be used to test strings and numbers.

    • [[ is a function that is similar to [ but is more robust.

    So, what you observed is that when using [ and [[ you are testing the strings true and false. All strings that do not have the length 0 are considered true so both true and false will be seen as true.

    I thought the entire premise of the brackets was to enable additional functionality like && and ||,

    You can execute multiple programs/functions too:

    if false || true; then
        # do something
    fi
    

    ... and combining executing programs/functions with testing strings is also possible:

    if ( false || true ) && [[ "$foo" == "$bar" ]]; then
        # do something
    fi