Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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
like image 665
dominique120 Avatar asked Jan 09 '14 03:01

dominique120


People also ask

How do you exit an if statement in shell script?

If you want the script to exit, use the exit command. If you want the function to return so that the rest of the script can continue, use return as I have done here.

How do you break out of a loop in shell?

The break command terminates the loop (breaks out of it), while continue causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle. The break command may optionally take a parameter.

What does if [- S mean in bash?

The -s test returns true if. [...] if file exists and has a size greater than zero. This is documented in the bash manual, and also in the manual for the test utility (the test may also be written if test -s file; then ).

What does \r do in bash?

The -r tests if the file exists and if you have read permission on the file. Bash scripting tutorial - if statement. The meaning of -r depends on what program/command it is given as an argument for. In this case it is for [ , and means to check whether the file named by the next argument is readable.


2 Answers

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
like image 87
ruakh Avatar answered Oct 13 '22 04:10

ruakh


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.

like image 26
John B Avatar answered Oct 13 '22 03:10

John B