TrumanWong

break

End the for, while or until loop.

Summary

break [n]

The main purpose

  • End the for, while or until loop, and you can specify how many levels of loops to exit.

Parameters

n (optional): an integer greater than or equal to 1, used to specify how many levels of loops to exit.

return value

Returns successful unless n is less than 1.

example

# The default value of the optional parameter n of break is 1.
# Continue execution from the outer for loop.
for((i=3;i>0;i--)); do
   for((j=3;j>0;j--)); do
     if((j==2)); then
       #The result is the same when changing to break 1
       break
     fi
   printf "%s %s\n" ${i} ${j}
   done
done
# Output results
3 3
twenty three
1 3
# When n is 2:
# Exit the two-level loop and end.
for((i=3;i>0;i--)); do
   for((j=3;j>0;j--)); do
     if((j==2)); then
       break 2
     fi
   printf "%s %s\n" ${i} ${j}
   done
done
# Output results
3 3

Notice

  1. This command is a built-in bash command. For related help information, please see the help command.