complex if statement syntax without using 'if ..' keyword in ksh.

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?

[ <condition> ] && ( <statement1>; <statement2>) || <statement>

Absolutely - I tend to use this syntax a lot (note the braces run the command in the current shell instead of a subshell):

[[ condition ]] && { blah1; } || { blah2; }

You can easily continue on multiple lines:

[[ condition && other_condition ]] && {
     everything_looks_good
    } || {
     uh_oh_spaghettios
     print_usage
}

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;}

This is not quite true. The program flow depends on the exit code of the statement between '&&' and '||'. For example:

bash-3.00$ true && { echo 1; false; } || echo 2
1
2

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.

2 Likes

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..