how to 'break' out of an if loop in bash?

2019-04-09 13:45发布

When I use break in an if loop in bash it tells me its not valid for bash, what can I use instead?

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

标签: bash shell
4条回答
forever°为你锁心
2楼-- · 2019-04-09 13:59

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^^}

查看更多
我命由我不由天
3楼-- · 2019-04-09 14:12

For this example, I think it makes more sense to use case.

case $ans1_1 in
    y)fedoraDeps;;
    n);;
    *) echo "Answer 'y' or 'n'";;
esac

From man bash:

If the ;; operator is used, no subsequent matches are attempted after the first pattern match.

查看更多
霸刀☆藐视天下
4楼-- · 2019-04-09 14:15

This sounds like an ideal case for the select command:

PS3="Please make a selection   >"
select foo in 'y' 'n'; do
    case $foo in
        'Y')
            fedoraDeps
            ;;
        'y')
            fedoraDeps
            ;;
        'n')
            break
            ;;
     esac
done
查看更多
做自己的国王
5楼-- · 2019-04-09 14:21

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 [[ $ans1_1 = y ]]; then
    fedoraDeps
elif [[ $ans1_1 = n ]]; then
    :
else
    echo "Answer 'y' or 'n'"
fi
查看更多
登录 后发表回答