天天看点

while循环

while循环

while condition; do

循环体

done

condition:循环控制条件:进入循环之前,先做一次判断;每一次循环之后会再次做判断;

条件为true,则执行一次循环;直到条件测试状态为false终止循环;

因此:condition中一般有循环控制变量;而此变量的值会在循环中不断的被修正;

实例:求100以内的正整数和;

#!/bin/bash

#

declare -i sum

declare -i i=1

while [ $i -le 100 ];do

let sum+=$i

let i++

echo "$sum

ping命令探测172.16.6.0-254在线的主机

declare -i ip=1

declare -i up=0

declare -i down=0

while [ $ip -le 254  ];do

 ping -w 1 172.16.6.$ip &>/dev/null 

if [ $? -eq 0 ];then

echo "172.16.6.$ip is online"

let up++ 

else

echo "172.16.6.$ip is down" 

let down++

fi

let ip++

echo "online is $up"

echo "down is $down" 

打印九九乘法表

for x in {1..9};do

for y in `seq 1 $x`;

do 

echo -e -n "$[x]X$[y]=$[$x*$y]\t"

echo

declare -i x=1

declare -i y=1

while [ $x -le 9 ];do

while [ $y -le $x ];do

echo -e -n "$y*$x=$[$y*$x]\t"

let y++

let y=1

let x++

利用random生成10个随机数,输出这10个数,并显示其中最大的和最小的;

declare -i max=0

declare -i min=0

rand=$RANDOM

echo $rand

max=$rand

min=$rand

while [ $i -le 9 ];do

if [ $rand -gt $max ];then

if [ $rand -lt $min ];then

echo "max=$max"

echo "min=$min"

while [ $i -le 10 ];do

if [ $i -eq 1 ];then

   max=$rand

   min=$rand

     本文转自阿伦艾弗森 51CTO博客,原文链接:http://blog.51cto.com/perper/1954274,如需转载请自行联系原作者