欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

shell编程之while循环

程序员文章站 2024-03-23 22:45:22
...

1.while循环的语法结构如下

while expression
do 
     command
done

将测试expression的返回值,如果返回值为真则执行循环体,为假则不执行。例如:

[[email protected] ~]# cat while01.sh 
#!/bin/bash
count=5
while [ $count -gt 0 ]
do 
   echo -n "$count"
   let count-=1
done
echo
[[email protected] ~]# sh while01.sh 
54321

2.while循环比较经典的用法是按行读取文件,例如:

[[email protected] ~]# cat while02.sh 
#!/bin/bash
cat score.txt | while read LINE
do
   NAME=`echo $LINE | awk '{print $1}'`
   AGE=`echo $LINE | awk '{print $2}'`
   SEX=`echo $LINE | awk '{print $3}'`
   echo "My name is $NAME,I'm $AGE years old,I'm a $SEX"
done
[[email protected] ~]# sh while02.sh 
My name is John,I'm 30 years old,I'm a boy
My name is lily,I'm 40 years old,I'm a girl

3.while的无限循环
主要有3种形式:
方法一:

while (1)
do 
     command
done

方法二:

while true
do 
     command
done

方法三:

whiledo 
     command
done