How does nested if/then/elseif work in bash? [closed]
·
Answer a question
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"
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
更多推荐

所有评论(0)