Search code examples
bashif-statementshshort-circuiting

Functional difference between if-then and command group


Is there any functional advantage of using a simple if-then statement such as

if [ … ]; then
do

over using short-circuit list evaluators with command groups such as

[ … ] && {
}

Of course, if-then is the standard way of writing it, but is there any actual difference/advantage from a functional point of view?

Using () instead of {} would spawn a new subshell, thus creating a new scope for variables inside the if-then block.


Solution

  • Not with your example, but the commonly seen

    condition && foo || bar
    

    is not the same as

    if condition
    then
      foo
    else
      bar
    fi
    

    In the former case, bar will run not only if condition fails, but if foo fails.