Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does nested if/then/elseif work in bash? [closed]

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" 
like image 810
Andrew Tsay Avatar asked Mar 10 '13 21:03

Andrew Tsay


People also ask

Can you nest if statements in bash?

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.

How do you use multiple IF statements in shell script?

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.

What statement ends an if statement in a Bash script?

The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword.

What is difference between if-else Fi and if Elif else Fi statement?

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.


1 Answers

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 
like image 139
mikyra Avatar answered Oct 14 '22 05:10

mikyra