It saves me lot of typing and space/lines when I do not use full 'if' keyword and construct, instead use ..
[ <condition> ] && <statement> || <statement>
that perfectly replaces..
if [ <condition> ]; then
<statement>
else
<statement>
fi
Can I use following syntax when I want to add multiple statements under 'if' or 'else' conditions? or does it have any down side to it compared to traditional 'if' 'else' construct?
if you want to put more than one command in such a command style,you should use brace curly---{},NOT ().The latter means execute these commands in a subshell.Look:
[ true ] && ( echo "yes,you can use it";echo $BASH_SUBSHELL;)
and this one
[ true ] && { echo "yes,you can use it";echo $BASH_SUBSHELL;}
If you were right, then only "1" should be printed, but as you can see, both echo statements are being executed. Whereas this executes as expected:
bash-3.00$ if true
> then
> echo 1
> false
> else
> echo 2
> fi
1
---------- Post updated at 10:24 ---------- Previous update was at 10:18 ----------
The reason is that the whole expression is evaluated as a logical expression:
A AND B OR C
If A is true, then B is evaluated. And if B is false, then the expression (A AND B) is false. Which leads to the evaluation of C. The value of the whole expression is then the value of C (true or false)
If (A AND B) is true, then value of the whole expression is true and it is not necessary to evaluate C.
Thaks hergp, that is what I am looking for.. I was wondering what makes my code fail, now I found answer for it.
Short-cut syntax for 'if' construct is really very un-safe and does not replace standard structure. God forbid a un-expected issue makes your last statement in if condition fail, it would cause control go into else part. If its doing a critical work in Production, you will go nuts as to what hit this logic :-)!
Does any one dispute my conclusions? If not stop using short-cut 'if' construct in business critical programs..