4

Given your trying to check that a variable is not empty and not some other value as in the following code:

if [ ! -z "$foo" ] && [[ ${foo} != "bar" ]]; then

what is the best practice for accomplishing this. I've seen bash conditionals written several ways including the following...

if [[ ! -z "$foo" && ${foo} != "bar" ]]; then

I understand there is a difference when using the single brackets and the double, I'm more concerned with when to put the && or || inside the brackets or out.

iamnewton
  • 329
  • 3
  • 9

2 Answers2

7

Put &&/|| inside brackets for [[ ]]. Outside is also accepted.

Put &&/|| outside brackets for [ ]. Inside is NOT allowed.

This is due to the fact that && binds normal commands together based on return value, e.g.

wget file && echo "Success"

[, despite its funny name, is a regular command and obeys the same rules as e.g. wget or echo.

[ foo || bar ] is two commands, [ foo and bar ], neither of which are valid.

[[ .. ]] on the other hand is not a normal command but special shell syntax. [[ foo || bar ]] is a single command, and interpretted accordingly.

that other guy
  • 116,971
  • 11
  • 170
  • 194
2

To complete the previous answers :

if [[ ! -z $foo && $foo != "bar" ]]; then ...
# [[ will execute the two conditions with "and" operator in a single instruction

Is equivalent of :

if [[ ! -z $foo -a $foo != "bar" ]]; then ...
# [[ will execute the two conditions with "and" operator in a single instruction

But not equivalent of :

if [[ ! -z $foo ]] && [[ $foo != "bar" ]]; then ...
# second [[ will be executed if the first success ($? = 0)

-a (and) and -o (or) will work with test and [.

See man test to get more details ;)

Otherwise, no need to protect your variables by doubles quotes with [[ and no need to use delimiters (${}) in this case.

Here is a reminder about the necessity (or not) to protect your variables with double quotes..

Community
  • 1
  • 1
Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32