break语句

时间:2019-04-16 23:59:05  来源:igfitidea点击:

使用break语句从FOR、WHILE或UNTIL循环中退出,即停止循环执行。

语法

break 

或者

break N

示例

for循环中的break语句

#!/bin/bash
match=  # fileName
found=0   # set to 1 if file found in the for loop

# show usage
[ $# -eq 0 ] && { echo "Usage: 
#!/bin/bash
# set an infinite while loop
while :
do
	read -p "Enter number ( -9999 to exit ) : " n
        
        # break while loop if input is -9999  
	[ $n -eq -9999 ] && { echo "Bye!"; break; }

	isEvenNo=$(( $n % 2 ))  # get modules 
        [ $isEvenNo -eq 0 ] && echo "$n is an even number." || echo "$n is an odd number."

done
fileName"; exit 1; } # Try to find file in /etc for f in /etc/* do if [ $f == "$match" ] then echo "$match file found!" found=1 # file found break # break the for looop fi done # noop file not found [ $found -ne 1 ] && echo "$match file not found in /etc directory"

while循环中的break语句

   for i in something
   do
      while true
      do
         cmd1
         cmd2
         [ condition ] && break 2
      done
   done

shell中如何退出嵌套循环

嵌套循环说明在循环中还有循环。通过添加 break n语句,可以打破嵌套循环中的指定层。n是嵌套的层数。
例如,下面的代码会跳出第二个done语句:

##代码##