天天看点

until-continue-break-for-case

until 循环

until conditon ;do

循环体

done

进入条件:false

退出条件:true

continue[N]:提前结束第N层的本轮循环,而直接进入下一轮判断;

while conditon;do

cmd1

..

if conditon;then

continue

fi

cmd

...

break[N];提前结束循环;

cmd..

break

求质数

#!/bin/bash

#

for ((i=2;i<=$1;i++));do

        for ((j=2;j<=i/2;j++));do

        if ((i%j==0));then

#       echo "$i 不是质数。。"

        break

        fi

        done

if ((j>i/2));then

#       echo ".................$i 是素数。。。。。。。。。。。。"

echo -n "$i,"

    fi

实例:求100以内所有偶数之和

declare -i i=0

declare -i sum=0

while [ $i -le 100 ];do

let i++

if [ $[$i%2] -eq 1 ];then

let sum+=$i

echo "$sum"

创建死循环

while true;do

until false; do

每三秒检查用户是否登录

read -p "Enter a user name :" username

if who | grep "^$username" &>/dev/null;then

sleep 3

echo "$username logged on." >> /tmp/user.log

while !(until两种方式都可以)  who | grep "^$username" &>/dev/null;do

while循环的特殊用法:

while read line; do

done < /path/from/somefile #输入重定向

注意:依次读取文件的每一行,且将行赋值给变量line

找出id号为偶数的所有用户,显示其用户名和ID号

查找id为偶数的用户

while read line ;do

if [ $[ `echo $line | cut -d: -f3` % 2 ] -eq 0 ];then

echo -e -n "username:`echo $line | cut -d: -f1`\t"

echo "uid:`echo $line | cut -d: -f3 `"

done < /etc/passwd

for循环的特殊格式:

for((控制变量初始化;条件判断表达式;控制变量的修正表达式));do

求100以内所有正整数之和

for ((i=1;i<=100;i++));do

echo $sum

九九乘法表

        #

        for ((x=1;x<=9;x++));do

                        for((y=1;y<=$x;y++));

        do 

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

        echo

根据提示输入命令。返回相应的信息。

cat << EOF

cpu)show cpu information

mem)show memory information

disk)show disk information

quit)quit;

=============================

EOF

read -p "Enter a option:" cmd

while [ "$cmd" != 'cpu' -a "$cmd" != 'mem' -a "$cmd" != 'disk' -a "$cmd" != 'quit' ] ;do

read -p "error cmd ...请重新输入:" cmd

if [ $cmd == cpu ];then

lscpu

elif [ $cmd == mem ];then

free

elif [ $cmd == disk ];then

fdisk -l

else

echo "Quit"

exit 0

条件判断:case语句

case 变量引用 in

PAT1)

分之1

;;

PAT2)

分之2

PAT3)

分之3

*)

默认分之

esac

case "$cmd" in

cpu)

mem)

disk)

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

上一篇: while循环