while语句
1、语法格式
while 测试条件; do 语句1 语句2 done
2、常见用法
2.1、while计算和
#!/bin/bash #定义变量 declare -i sum=0 declare -i i=1 #两种写法 while [ $i -le 100 ];do #while (($i<101));do let sum+=i let ++i #下方这两行语句也可以实现变量Sum和i的重新赋值 #Sum=$[$Sum+$i] #i=$[$i+1] done echo "1到100之间所有整数的和为$Sum"
2.2、while read line读取文件
#!/bin/bash while read line; do User=`echo $line |cut -d: -f 1` Shell=`echo $line |cut -d: -f 7` echo "用户$User的默认shell是$Shell" done < "/etc/passwd"
#!/bin/bash cat /etc/passwd|while read line; do User=`echo $line |cut -d: -f 1` Shell=`echo $line |cut -d: -f 7` echo "用户$User的默认shell是$Shell" done
3、死循环
while (());do 语句1 done while [1 -gt 0];do 语句1 done while true;do 语句1 done