'Bash -a vs bash && [duplicate]

I have this bash statement:

if ls > /dev/null 2>&1 -a ls > /dev/null 2>&1; then
    echo "true"; 
else 
    echo "false"; 
fi

Which gives me "false". But I know ls will always return 0 (i.e. true). I had thought that -a was an AND statement.

When I change this to:

if ls > /dev/null 2>&1 && ls > /dev/null 2>&1; then
    echo "true"; 
else 
    echo "false"; 
fi

It works. What's going on differently here? Is -a not an AND operator?



Solution 1:[1]

&& is the correct way to perform a short-circuiting logical AND in bash.

-a is a test operand (test is the command also named [). It does not mean AND in any other context (built into bash; it is also a predicate in find, for example). Moreover, the POSIX specification for test has it marked "obsolescent"; search for OB within the linked page.

The above is also to say that [ -n "$foo" ] && [ -n "$bar" ], or [[ $foo && $bar ]], is better practice than [ -n "$foo" -a -n "$bar" ].

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1