D15
break和continue是Bash中的循环控制命令,其用法与其他编程语言中的同名语句一致。
1. break语句
用于从for、while、until或select循环中退出、停止循环的执行。
语法:
break [n]
n代表嵌套循环的层级,如果指定了n,break退出n级嵌套循环。如果没有指定n或n<1,则退出状态码为0,否则退出状态码为n。
$ cat break.sh #!/bin/bash #20200525 [ $# -eq 0 ] && { echo "Usage: $0 filepath"; exit 1; } #如果没有输入参数,则打印提示并退出 match=$1 #用位置参数获取输入 found=0 for file in ./test/* do echo $file if [ $file == "$match" ] then echo "The file $match was found!" found=1 break #退出for循环 fi done [ $found -ne 1 ] && echo "The file $match not found in ./test" #执行 $ ./break.sh a.txt ./test/a.txt ./test/c.txt ./test/d.txt The file a.txt not found in ./test $ ./break.sh ./test/a.txt ./test/a.txt The file ./test/a.txt was found!
省略P167嵌套循环示例
2. continue语句
用于跳过循环体中剩余的命令直接跳转到循环体的顶部,重新开始下一次重复。
continue语句可用于for、while或until循环。
语法:
continue [n]
示例:
$ cat continue.sh #!/bin/bash #20200525 [ $# -eq 0 ] && { echo "Usage: $0 filepath"; exit 1; } #如果没有输入参数,则打印提示并退出 match=$1 #用位置参数获取输入 found=0 for file in ./test/* do echo $file if [ $file != "$match" ] then echo "The file $file does not match!" continue #不匹配时跳转到下一次循环 fi found=1 echo "The file $match was found once!" done [ $found -lt 1 ] && echo "The file $match not found in ./test" || echo "The file $match was found in ./test" #执行 $ ./continue.sh ./test/c.txt ./test/a.txt The file ./test/a.txt does not match! ./test/c.txt The file ./test/c.txt was found once! #此处匹配,因此继续执行了下面的echo语句 ./test/d.txt The file ./test/d.txt does not match! The file ./test/c.txt was found in ./test
$ ./continue.sh a.txt ./test/a.txt The file ./test/a.txt does not match! ./test/c.txt The file ./test/c.txt does not match! ./test/d.txt The file ./test/d.txt does not match! The file a.txt not found in ./test
省略P168的示例,以break的示例改造。
本节结束