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
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.
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.
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 ).
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With