I was answering a question and assumed that
if [ $(command) ]; then ...
is always equivalent to
if command; then ...
However, I got a couple of counter examples:
$ [ $(true) ] && echo "yes" || echo "no"
no
$ if true; then echo "yes"; else echo "no"; fi
yes
And:
$ if echo "$xxxx"; then echo "yes"; else echo "no"; fi
yes
$ [ $(echo "$xxx") ] && echo "yes" || echo "no"
no
In both cases the problem lies in true
and echo $xxxx
(unset variable) do not return anything, so [ ]
evaluates to False (by definition in man test
), whereas echo $xxxx
is successful so its return code is 0 and, therefore, the if
condition evaluates to True.
However, I wonder: when can we assume both checks are equivalent? Is this a risky thing to assume or it is reliable in most of the cases?