shell中跳出循环语句break和continue

  在使用while或for循环语句过程中,也许碰到某个特殊条件,我们需要跳过当次循环或整个循环,这是就需要借助break和continue。

  break表示跳出本层循环,break n表示跳出循环的层数。continue表示跳过本次循环,continue n表示跳过n次循环。

  实例如下:

[root@youxi1 ~]# vim a.sh
#!/bin/bash
for ((i=0;i<=4;i++)) ; do
  echo $i
  case $i in
  1)
    echo "This is one"
    ;;
  2)
    continue
    echo "This is two"
    ;;
  3)
    break
    echo "This is three"
    ;;
  4)
    echo "This is four"
    ;;
  esac
done
[root@youxi1 ~]# sh a.sh 
0  #0的时候没有匹配项
1
This is one
2  #2的时候跳过了当前循环
3  #3的时候直接退出了循环

  多层循环嵌套实例:

[root@youxi1 ~]# vim a.sh
#!/bin/bash
for ((i=1;i<10;i++)) ; do
  for ((j=1;j<=i;j++)) ; do
    if [ j -eq 4 ] ; then
      continue
    fi
    for ((k=1;k<=j;k++)) ; do
      if [ k -gt 5 ] ; then
        break 2
      fi
      echo -n $i"*"$j"*"$k"="$[i*j*k]" "
    done
  done
  echo
done
[root@youxi1 ~]# sh a.sh 
1*1*1=1 
2*1*1=2 2*2*1=4 2*2*2=8 
3*1*1=3 3*2*1=6 3*2*2=12 3*3*1=9 3*3*2=18 3*3*3=27 
4*1*1=4 4*2*1=8 4*2*2=16 4*3*1=12 4*3*2=24 4*3*3=36 
5*1*1=5 5*2*1=10 5*2*2=20 5*3*1=15 5*3*2=30 5*3*3=45 5*5*1=25 5*5*2=50 5*5*3=75 5*5*4=100 5*5*5=125 
6*1*1=6 6*2*1=12 6*2*2=24 6*3*1=18 6*3*2=36 6*3*3=54 6*5*1=30 6*5*2=60 6*5*3=90 6*5*4=120 6*5*5=150 6*6*1=36 6*6*2=72 6*6*3=108 6*6*4=144 6*6*5=180 
7*1*1=7 7*2*1=14 7*2*2=28 7*3*1=21 7*3*2=42 7*3*3=63 7*5*1=35 7*5*2=70 7*5*3=105 7*5*4=140 7*5*5=175 7*6*1=42 7*6*2=84 7*6*3=126 7*6*4=168 7*6*5=210 
8*1*1=8 8*2*1=16 8*2*2=32 8*3*1=24 8*3*2=48 8*3*3=72 8*5*1=40 8*5*2=80 8*5*3=120 8*5*4=160 8*5*5=200 8*6*1=48 8*6*2=96 8*6*3=144 8*6*4=192 8*6*5=240 
9*1*1=9 9*2*1=18 9*2*2=36 9*3*1=27 9*3*2=54 9*3*3=81 9*5*1=45 9*5*2=90 9*5*3=135 9*5*4=180 9*5*5=225 9*6*1=54 9*6*2=108 9*6*3=162 9*6*4=216 9*6*5=270 

  

原文地址:https://www.cnblogs.com/diantong/p/11698737.html