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

我猜你的问题是关于许多语法中包含的悬而未决的歧义;在 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 回答