linux if/elif/fi 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12676541/
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 14:28:40  来源:igfitidea点击:

linux if / elif / fi command

linuxbashif-statementsh

提问by Benoit Paquette

I have a question. If my ifstatement is true, does it skip the elifcheck and goes straight to fior does it still check the elifstatements?

我有个问题。如果我的if语句是true,它是跳过elif检查并直接转到fi还是仍然检查elif语句?

Example of the script :

脚本示例:

if [ argument1 || argument2 ]  
     then  
          do something.  
elif [ argument2 || argument3 ]  
     then  
          do something.  
elif [ argument2 || argument4 ]  
     then  
          do somthing.  
else  
          do somthing else.  
fi  

My question being that I would want my elifstatements to still be checked if my first ifstatement was true. I would also want my elifstatements to be checked if my first elifstatement was true... etc. Basically I would want all my ifand elifstatements to all be checked.

我的问题是,elif如果我的第一个if陈述是真的,我希望我的陈述仍然受到检查。elif如果我的第一个elif陈述是true……等,我也希望我的陈述得到检查。基本上我希望所有我的ifelif陈述都得到检查。

NB. I realize I could change all of my elifto ifstatements and this would probably resolve my issue since all ifstatements would get checked. But this question is also out of curiosity and better knowledge of the ifand elifstatements.

注意。我意识到我可以更改我所有的eliftoif语句,这可能会解决我的问题,因为所有if语句都会被检查。但这个问题也是出于好奇和更好的认识ifelif陈述的。

Please let me know if you need more info.

如果您需要更多信息,请告诉我。

回答by Brian Campbell

The elifstatement is not checked if one of the prior ones matched. elifis short for "else if"; it means that you should check this other condition if the previous one did not match.

elif如果先前的语句之一匹配,则不会检查该语句。elif是“else if”的缩写;这意味着如果前一个条件不匹配,您应该检查另一个条件。

As you say, you can just use multiple ifstatements for your use case.

正如您所说,您可以if为您的用例使用多个语句。

回答by dogbane

Once a condition is met, the ifstatement terminates and the remaining elifconditions will not be checked.

一旦满足某个条件,该if语句将终止并且elif不会检查其余条件。

Example:

例子:

if echo foo
then
   echo "in foo"
elif echo bar
then
   echo "in bar"
fi

prints

印刷

foo
in foo

If you want them all checked, then you need to break it into multiple if-statements as you suggested.

如果您希望它们都被选中,那么您需要按照您的建议将其分解为多个 if 语句。