33

構文は bash でどのように機能しますか? これは、C スタイルの if else ステートメントの擬似コードです。例えば:

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"
4

1 に答える 1

78

あなたの質問は、多くの文法に含まれるelseのあいまいさに関するものだと思います。bash では、そのようなことはありません。すべては、if ブロックの終わりを示すifコンパニオンによって区切られなければなりません。fi

この事実 (他の構文エラーに加えて) を考えると、例が有効な bash スクリプトではないことに気付くでしょう。エラーのいくつかを修正しようとすると、次のような結果が得られる場合があります

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
于 2013-03-10T21:42:55.693 に答える