This question pertains specifically to shell scripts, but could be about any programming language.
Is there any difference between using multiple if
statements and using elif
statements in shell scripts? And, a case
statement would not work in my situation.
Summary: By using an ELSE IF structure instead of multiple IF we can avoid “combined conditions” ( x<y && y<z ). Instead we can use a simplified condition (y<z). Furthermore ELSE IF is more efficient because the computer only has to check conditions until it finds a condition that returns the value TRUE.
Switch statement works better than multiple if statements when you are giving input directly without any condition checking in the statements. Switch statement works well when you want to increase the readability of the code and many alternative available.
In this case it is fine, in fact in most cases it is. The problem only occurs when you have many nested in many and so it can become hard to read and you may forget something, but that's readability, there is nothing wrong in the logic for using nested if statements.
Yes, potentially. Consider this (C#, Java, whatever):
int x = GetValueFromSomewhere(); if (x == 0) { // Something x = 1; } else if (x == 1) { // Something else... }
vs this:
int x = GetValueFromSomewhere(); if (x == 0) { // Something x = 1; } if (x == 1) { // Something else... }
In the first case, only one of "Something" or "Something else..." will occur. In the second case, the side-effects of the first block make the condition in the second block true.
Then for another example, the conditions may not be mutually exclusive to start with:
int x = ...; if (x < 10) { ... } else if (x < 100) { ... } else if (x < 1000) { ... }
If you get rid of the "else" here, then as soon as one condition has matched, the rest will too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With