How does the syntax work in bash? This is my pseudocode for C style if else statements. For instance:
If (condition) then echo "do this stuff" elseif (condition) echo "do this stuff" elseif (condition) echo "do this stuff" if(condition) then echo "this is nested inside" else echo "this is nested inside" else echo "not nested"
You can make the nest as deep as you want, though it will continue to grow in complexity. In this tutorial, you will learn how to use nested if statements in a Bash script on a Linux system. Check some of the examples below to see how nested if statements work.
To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword.
In several other languages, the elif is written as “elseif” or “else if”. The elif statement helps us to make decisions among different choices. The “if' keyword is followed by the condition you want to check. In this if-else-if conditional statement, the expressions are evaluated from top to bottom.
I guess your question is about the dangling else ambiguity contained in many grammars; in bash there isn't such a thing. Every if
has to be delimited by a companion fi
marking the end of the if block.
Given this fact (besides other syntactic errors) you'll notice your example isn't a valid bash script. Trying to fix some of the errors, you might get something like this
if condition then echo "do this stuff" elif condition then echo "do this stuff" elif condition then echo "do this stuff" if condition then echo "this is nested inside" # this else _without_ any ambiguity binds to the if directly above as there was # no fi closing the inner block else echo "this is nested inside" # else # echo "not nested" # as given in your example is syntactically not correct ! # We have to close the last if block first as there's only one else allowed in any block. fi # now we can add your else .. else echo "not nested" # ... which should be followed by another fi fi
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