课后练习之while循环

while循环

编写脚本,求100以内所有正奇数之和

[root@Learn-HC-Nn ~/data]
# cat js_sum_while.sh 
#!/bin/bash
sum=0
i=1
while [ $i -le 100 ];do
    sum=$[sum+i]
    i=$[$i+2]
done
echo $sum

j=0
for i in {1..100};do
    [ $[i%2] == 1 ] && j=$[j+i]  
done
echo $j

编写脚本,提示请输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态,并统计在线和离线主机各多少
这道题最后的结果有问题,如果有大佬帮忙改改最好了

[root@Learn-HC-Nn ~/data]
# cat net.sh 
#!/bin/bash
read -p "Please enter a ipaddress :" IP
[ $IP == `echo $IP|egrep -o "\<(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\>"` ] || (echo "This is not a correct IP address";exit 10) 
net=`echo $IP|cut -d. -f1,2,3`
id=1
up=0
down=0
while [ $id -lt 255 ];do
        {
        ping -c1 -w1 $net.$id &>/dev/null && (let up+=1;echo "$net.$id is up") || (let down+=1;echo "$net.$id is down")
        }&
        let id+=1
done
echo "Host noline status"
echo "up : $up  donw : $down"
wait

编写脚本,打印九九乘法表

[root@Learn-HC-Nn ~/data]
#for 循环写法
# cat 9-9.sh 
#!/bin/bash
for i in {1..9};do
    for j in `seq $i`;do
        echo -e "${j}x${i}=$[j*i]\t\c"
        done
    echo
done

#while 循环写法
x=1
while [ $x -lt 10 ];do
    for y in `seq $x`;do
    printf "%dx%d=%d\t" $y $x $[y*x]
    done
    echo
    let x+=1
done

编写脚本,利用变量RANDOM生成10个随机数字,输出这个10数字,并显示其中的最大值和最小值

[root@Learn-HC-Nn ~/data]
# cat 21446.sh
i=0
while [ $i -lt 10 ];do
    echo $RANDOM >> ./num.txt
    let i+=1
done
MAX=`cat num.txt|sort -nr|head -1`
MIN=`cat num.txt|sort -n |head -1`
echo "MAX: $MAX    MIN: $MIN"

你可能感兴趣的:(课后练习之while循环)