0

I was just wondering if there's any practical difference between writing the following bash:

if [ <some condition> ]; then
  <some statement>
fi

and the following:

[ <some condition> ] && {
  <some statement>
}

Is there any difference in how this is executed, or are they equivalent?

1

There's not much logical nor linguistic difference at this point. But if you were to grow this into something bigger, then the verbose syntax with if gives more space for adding elifs and else. If you stick to the logical operators, then it will be much harder to read. Try it yourself.

For example, rewrite the following using && and/or ||.

if [ 1 -eq 2 ]; then echo ok; elif [ 1 -eq 1 ]; then echo lif; else echo el; fi
  • Also flow of logic: consider if A; then B; else C; fi versus A && B || C. Will C be executed when A succeeds but B fails? – glenn jackman Sep 28 '18 at 19:05
0

Basically, they are equivalent. In both cases the statement is executed only if the condition is true.

It is a difference in style, I prefer the first option.

  • 1
    @DopeGhoti Thanks. I though I remembered differently, but it seems that was false || false, not false && false. – RalfFriedl Sep 28 '18 at 18:31
0

Not all shells support:

[ <some condition> ] && {
  <some statement>
}

Some shells are supporting it by a executable in /usr/bin/[.

To test if your shell are using /usr/bin/[ just do:

$ builtin [
sh: 1: builtin: not found

This means the shell is using /usr/bin/[, but if you get something else your shell support it...

But bash has the support.

  • Umm... Whether the shell uses its built-in [ or the external [ should not really matter. – Kusalananda Sep 28 '18 at 19:42
  • Well better if i say not all environment have external [ ? – Luciano Andress Martini Sep 28 '18 at 19:56
  • Aren't both if/then and && part of the POSIX shell syntax? Sure, there are non-POSIX shells that might not support one, but then they might also not support the other, so... – ilkkachu Sep 28 '18 at 20:50
  • @LucianoAndressMartini if a shell doesn't have a [ built-in, it will use the external /bin/[ for both if [...]; then and [..] &&. [ is not part of the syntax, if grep ...; then ... works just file. Also, your shell is telling you that it cannot find a built-in, function or external command named builtin, not that [ is not a built-in ;-) – mosvy Sep 28 '18 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.