shell script 之六:循环 while

while循环

基本语法:

while <条件>
do
    <命令>
done

例1:依次打印数字

#!/bin/bash
#while test
#by sunny
i=10
while ((i<100));
do
sleep 1
  echo "the num is $i"
  ((i++))
  if [ $i -gt 15 ];then    # i超过15会停止循环跳出
    break
  fi
done

执行 sh while1.sh 
the num is 10
the num is 11
the num is 12
the num is 13
the num is 14
the num is 15

 

 

while循环更多地用于读取标准输入的内容来实现循环,while read line  将标准输入作为值赋值给变量line

#!/bin/sh
#by sunny at201606
while read line
do
  echo $line
done <hello.txt  #将hello.txt中的内容赋值给line

~ cat hello.txt 
hello 
world 
byebye

 

posted @ 2018-03-22 14:50  sunny18  阅读(535)  评论(0编辑  收藏  举报