2013-03-10 7 views
9

Wie funktioniert die Syntax in bash? Dies ist mein Pseudocode für C-Stil, wenn sonst Anweisungen. Zum Beispiel:Wie verschachtelt if/then/elseif in bash?

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" 

Antwort

25

Ich denke, Ihre Frage ist über die dangling sonst Zweideutigkeit in vielen Grammatiken enthalten; In der Bash gibt es so etwas nicht. Jede if muss durch einen Begleiter fi begrenzt werden, der das Ende des if-Blocks markiert.

Angesichts dieser Tatsache (neben anderen syntaktischen Fehlern) werden Sie feststellen, dass Ihr Beispiel kein gültiges Bash-Skript ist. Versuchen Sie, einige der Fehler zu beheben, die Sie möglicherweise so etwas bekommen können

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

Perfekt! Vielen Dank –