Shell 流程控制 - while 循环
简介
-
while 循环用于不断执行一系列命令,也用于从输入文件中读取数据。
-
’ while ’ 后为循环执行的条件,为 " true " 或者 " : " 时,便是无限循环。
-
循环的退出:
- ’ continue ':终止当此次前循环提前进入下个循环 。
- ’ break ’ :终止当前所在语句所有动作进行语句外的其他动作 。
- ’ exit ’ :脚本退出 。
-
’ do ’ :后面为循环要执行的命令。
-
’ done ’ :循环结构结束的标志。
-
语法格式
while condition do command done
-
写成一行
while test-commands; do consequent-commands; done
参考文章
- 参考文章:https://www.runoob.com/linux/linux-shell-process-control.html
- 官方文档:https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs
示例
- 无限循环示例: 判断文件类型,直到输入 ’ exit ’ 退出。
[root@ while]# cat check_file.sh #!/bin/bash while : do read -p "input file: " file if [ $file = "exit" ] then exit else echo "$file is `file $file | awk -F ":" '{print $2}'`" fi done [root@ while]# sh check_file.sh input file: test.sh test.sh is Bourne-Again shell script, ASCII text executable input file: ../while ../while is directory input file: /root /root is directory input file: /dev/null /dev/null is character special input file: exit [root@ while]#
- 有限循环:打印一到五。
[root@ while]# cat test.sh #!/bin/bash int=1 while (( $int<=5 )) do echo $int let "int++" done [root@ while]# sh test.sh 1 2 3 4 5 [root@ while]