Please note, that [] && cmd
是不一样的if ..
fi
construction.
Sometimes its behaviour its pretty similar and you can use
[] && cmd
instead of if .. fi
. But
only sometimes. If you have more then one command to execute if
condition or you need if .. else .. fi
be careful and
whatch the logic.
几个例子:
[ -z "$VAR" ] && ls file || echo wiiii
是不一样的
if [ -z $VAR ] ; then
ls file
else
echo wiii
fi
因为如果 ls
失败, echo
将被执行,如果,
将不会发生这种情况。
另一个例子:
[ -z "$VAR" ] && ls file && echo wiii
是不一样的
if [ -z "$VAR" ] ; then
ls file
echo $wiii
fi
虽然这种结构也会起作用
[ -z "$VAR" ] && { ls file ; echo wiii ; }
请注意;
后回声很重要,必须在那里。
所以我们可以说上面的恢复声明
[] && cmd
== if first command is successful
then execute the next one
if .. fi
== if condition (which may be the test
command as well) then execute command(s)
因此,对于 [
和 [[
仅使用
[
]之间的可移植性。
if
is POSIX compatible. So if you have to choose
between [
and if
choose looking at your
task and expected behaviour.