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
linux if / elif / fi command
提问by Benoit Paquette
I have a question. If my if
statement is true
, does it skip the elif
check and goes straight to fi
or does it still check the elif
statements?
我有个问题。如果我的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 elif
statements to still be checked if my first if
statement was true. I would also want my elif
statements to be checked if my first elif
statement was true
... etc. Basically I would want all my if
and elif
statements to all be checked.
我的问题是,elif
如果我的第一个if
陈述是真的,我希望我的陈述仍然受到检查。elif
如果我的第一个elif
陈述是true
……等,我也希望我的陈述得到检查。基本上我希望所有我的if
和elif
陈述都得到检查。
NB. I realize I could change all of my elif
to if
statements and this would probably resolve my issue since all if
statements would get checked. But this question is also out of curiosity and better knowledge of the if
and elif
statements.
注意。我意识到我可以更改我所有的elif
toif
语句,这可能会解决我的问题,因为所有if
语句都会被检查。但这个问题也是出于好奇和更好的认识if
而elif
陈述的。
Please let me know if you need more info.
如果您需要更多信息,请告诉我。
回答by Brian Campbell
The elif
statement is not checked if one of the prior ones matched. elif
is 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 if
statements for your use case.
正如您所说,您可以if
为您的用例使用多个语句。
回答by dogbane
Once a condition is met, the if
statement terminates and the remaining elif
conditions 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 语句。