12.Shell while循环 - morris131/morris-book GitHub Wiki

Shell while循环

while循环用于不断执行一系列命令,也用于从输入文件中读取数据,命令通常为测试条件。其格式为:

while command
do
   Statement(s) to be executed if command is true
done

命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。

基本while循环

如果COUNTER小于5,那么返回 true。COUNTER从0开始,每次循环处理时,COUNTER加1。运行上述脚本,返回数字1到5,然后终止。

while.sh

#!/bin/bash

COUNTER=1
while [ $COUNTER -le 5 ]
do
  echo $COUNTER
  COUNTER=`expr ${COUNTER} + 1`
done
# chmod +x while.sh
# ./while.sh s
1
2
3
4
5

while循环读取键盘信息

下面的例子中,输入信息被设置为变量FILM,按结束循环。

whileRead.sh

#!/bin/bash

echo 'type <CTRL-D> to terminate'
echo -n 'enter your most liked film: '
while read FILM
do
    echo "Yeah! great film the $FILM"
done
# chmod +x whileRead.sh
# ./whileRead.sh
type <CTRL-D> to terminate
enter your most liked film: Music Year
Yeah! great film the Music Year
⚠️ **GitHub.com Fallback** ⚠️