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

2019-04-09 13:36发布

问题:

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

回答1:

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


回答2:

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.



回答3:

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


回答4:

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



标签: bash shell