Linux 嵌套的 if/then/elseif 如何在 bash 中工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15327973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:13:33  来源:igfitidea点击:

How does nested if/then/elseif work in bash?

linuxbashnestedif-statement

提问by Andrew Tsay

How does the syntax work in bash? This is my pseudocode for C style if else statements. For instance:

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"

采纳答案by mikyra

I guess your question is about the dangling else ambiguity contained in many grammars; in bash there isn't such a thing. Every ifhas to be delimited by a companion fimarking the end of the if block.

我想你的问题是关于许多语法中包含的悬而未决的其他歧义;在 bash 中没有这样的事情。每个if都必须由fi标记 if 块结束的伴随分隔。

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

鉴于这一事实(除了其他语法错误),您会注意到您的示例不是有效的 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