On 2016-07-26, Janis Papanagnou <
janis_pa...@hotmail.com> wrote:
> On 26.07.2016 18:34, James wrote:
> [...]
>> In bash,
>>
>> if [ "$A" -a "$B" ]; then
>> do_something
>> fi
>>
>> This seems to fail if $A or $B is non-existent or empty. What is the correct way?
>
> The test operator -a tests for files, it's an unary operator.
Ther is a binary one, a Boolean AND: EXPR -a EXPR.
$ [ "" -a "" ] && echo true
$ [ "" -a "y" ] && echo true
$ [ "y" -a "" ] && echo true
$ [ "y" -a "y" ] && echo true
true
Indeed, the condition fails if $A or $B is non-existent or empty, or both are.
In the test syntax, here is a hack in that an empty string is false,
and a non-empty string is true (unless it looks like a predicate
operator, which "y" does not).
If A and B could contain anything, including something that looks like
a test operator, then we better use:
[ -n "$A" -a -n "$B" ]
I.e. use the -n predicate to explicitly test an argument for not
empty. Here, A can contain "-z" or whatever without causing confusion.
Also, if the test syntax is completely empty (no expression at all),
that is a false:
$ [ ] && echo true
Any word that doesn't look like an operator is true:
$ [ y ] && echo true
true
Thus, if you have a disciplined boolean variable V which is either
empty/unset or else contains a well-behaved representation of Boolean
true like "y", you can use this shorthand:
if [ $V ] ; then # Look, Ma, no double quotes or -n operator!
echo V is true
fi