while中的5种条件
1.数学比较
1 read -p "Num :" num1 2 while [ $num1 -gt 0 ] 3 do 4 echo 'greater' 5 sleep 1 6 7 done
2.字符串比较
1 read -p "enter the password:" pw 2 while [ $pw != password ] 3 do 4 read -p "enter the password:" pw 5 6 done 7 echo 'welcome'
3.检测文件是否存在
1 while [ ! -e /tmp/testfolder ] 2 do 3 echo '/tmp/testfolder not exist' 4 sleep 1 5 done
4.多个条件判断
1 read -p "money:" money 2 read -p "car:" car 3 read -p "house:" house 4 5 while [ $money -lt 100000 ] || [ $car -lt 1 ] || [ $house -lt 1 ] 6 do 7 echo 'no way!' 8 read -p "money:" money 9 read -p "car:" car 10 read -p "house:" house 11 done 12 echo 'Ok!'
5.赋值判断
1 read -p "char:" ch 2 3 while [ $ch != 'q' ] 4 do 5 echo "char is : $ch" 6 read -p "char:" ch 7 done 8 echo 'you just press q'
6.类似于for的写法
1 i=1 2 while [ $i -lt 10 ] 3 do 4 echo $i 5 i=$((i+1)) 6 done
7.while使用break还有continue的时候需要注意累加的顺序
1 i=1 2 while [ $i -lt 10 ] 3 do 4 echo $i 5 i=$(( i+1 )) 6 if [ $i -eq 5 ];then 7 continue 8 fi 9 #i=$(( i+1 )) continue时先累加,break时后累加 10 done
8.九九乘法表
1 n=1 2 while [ $n -lt 10 ] 3 do 4 for (( m=1;m<=$n;m++ )) #此处 m<=$n 如果写成 m<10 输出的样式会有很大的不同 5 do 6 echo -n -e "$m x $n = $((n*m))\t" 7 done 8 echo 9 n=$((n+1)) 10 done
如果将上面的for换成while 即双重while的嵌套
1 n=1 2 while [ $n -lt 10 ] 3 do 4 #for (( m=1;m<=$n;m++ )) 5 # do 6 m=1 7 while [ $m -lt $n ];do 8 9 echo -n -e "$m x $n = $((n*m))\t" 10 11 m=$(($m+1)) 12 done 13 echo 14 n=$((n+1)) 15 done
9.读取 passwd中的内容
1 while read i;do 2 echo $i 3 done < /etc/passwd
10.读取 passwd中的内容 仅显示第一列 第三列 第五列
1 IFS=$":" 2 while read f1 f2 f3 f4 f5 f6 f7;do 3 echo "$f1 $f3 $f5" 4 5 done < /etc/passwd
11.until
until和while的区别就是 until是条件为假才执行
打印 10-20
1 i=10 2 until [ $i -gt 20 ];do 3 echo $i 4 i=$((i+1)) 5 done