mercredi 31 janvier 2018

Why && better than -a in bash?

I've read man test and found:

NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead.

Can someone explain what ambiguously in -a and -o?

English is not my native language. As I understood, Kevin Braunsdorf and Matthew Bradburn (authors of this man page) advice us to use && instead of -a just because -a could be used as a key in another binaries, because -a could have different possible meanings.

So, -a is not associated with logical AND when we use test. It's not clear for someone, so people thinking like: "Hmm, what is that key? I don't know, not sure it is logical AND, I must visit man..."

The only reason I could find is that code with && is easier to read for people than code with -a (just an example):

With -a:

if [ -f "${my_var_with_filename}" -a -n "${my_another_array_var_with_filename[2]}" -o -r /just/path/to/file ]
then
...
fi

Same with &&:

if [ -f "${my_var_with_filename}" ] && [ -n "${my_another_array_var_with_filename[2]}" ] || [ -r /just/path/to/file ]
then
...
fi

As for me, both examples are syntactically complex, and it's hard to read bash code with multiple conditions, variables, array variables and logical operators.

So, my questions are:

  1. Do you agree with that -a and -o in test are "inherently ambiguous"?

  2. In multiple conditions, do you use -a(-o) or &&(||)?

  3. Someone has arguments to unequivocally name -a and -o "ambiguous"? Or it's just authors' opinion? Should they advice us to use && instead of -a based only on their opinion in man page?

Aucun commentaire:

Enregistrer un commentaire