如何在 bash 中“跳出”if 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21011010/
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
how to 'break' out of an if loop in bash?
提问by dominique120
When I use break
in an if loop in bash it tells me its not valid for bash, what can I use instead?
当我break
在 bash 的 if 循环中使用时,它告诉我它对 bash 无效,我可以使用什么代替?
The use case is, the user is asked a question and if he answers 'no', the script should skip to the next section.
用例是,用户被问到一个问题,如果他回答“否”,脚本应该跳到下一部分。
if [[ $ans1_1 = "y" ]]; then
fedoraDeps
elif [[ $ans1_1 = "n" ]]; then
break
else
echo "Answer 'y' or 'n' "
fi
回答by ruakh
if
statements are not "loops", so it doesn't make sense to break out of them. If you want one of your blocks to be a no-op, you can use the built-in :
command, which simply does nothing:
if
语句不是“循环”,因此脱离它们是没有意义的。如果你希望你的一个块是空操作,你可以使用内置:
命令,它什么都不做:
if [[ $ans1_1 = y ]]; then
fedoraDeps
elif [[ $ans1_1 = n ]]; then
:
else
echo "Answer 'y' or 'n'"
fi
回答by John B
For this example, I think it makes more sense to use case
.
对于这个例子,我认为使用case
.
case $ans1_1 in
y)fedoraDeps;;
n);;
*) echo "Answer 'y' or 'n'";;
esac
From man bash
:
来自man bash
:
If the ;; operator is used, no subsequent matches are attempted after the first pattern match.
如果;; 使用运算符,在第一个模式匹配后不会尝试后续匹配。
回答by DopeGhoti
This sounds like an ideal case for the select
command:
这听起来像是select
命令的理想情况:
PS3="Please make a selection >"
select foo in 'y' 'n'; do
case $foo in
'Y')
fedoraDeps
;;
'y')
fedoraDeps
;;
'n')
break
;;
esac
done
回答by Coder-guy
I agree that case is probably best. But you should probably cast to upper/lower case either way. For the way you had it:
我同意这种情况可能是最好的。但是您可能应该以任何一种方式转换为大写/小写。对于你的方式:
if [[ ${ans1_1,,} = "y" ]]; then
fedoraDeps
elif [[ ${ans1_1,,} = "n" ]]; then
:
else
echo "Answer 'y' or 'n' "
fi
Or, if you wanted uppercase ${ans1_1^^}
或者,如果您想要大写 ${ans1_1^^}