Shell中的循环语句

在编程语言中,循环语句是最基本的语法之一,在Shell(这里是Bash)中也不例外。把相关内容整理一下吧。

这里包括for/while/until循环,以及变量自增的语法实例。

Shell(以Bash为例)中的循环语句一般有for、while、until这几种,偶尔还有写错语法的时候,这里结合实例来自己总结一下。也为今后使用提供一个快捷的资料获取渠道。

一、for循环语句

实例1.1 对目录中的文件做for循环

#!/bin/bash
for x in
/var/log/*
do
        #echo "$x is a file living in /var/log"
       
echo $(basename $x) is a file living in
/var/log
done

注:这个$x获得的是绝对路径文件名;可以使用 “basename”
可执行程序来除去前面的路径信息。如果只引用当前工作目录中的文件(例如,如果输入 “for x in
*”),则产生的文件列表将没有路径信息的前缀。
实例1.2 对位置参数做for循环

#!/bin/bash

for thing in
"$@"
do
        echo you typed ${thing}.
done

实例1.3 for循环中用seq产生循环次数,加上C语言形式的for循环语句

#!/bin/bash

echo "for: Traditional form:
for var in …"
for j in $(seq 1 5)
do
        echo
$j
done

echo "for: C language form: for (( exp1; exp2; exp3
))"

for (( i=1; i<=5; i++ ))
do
        echo "i=$i"

done

二、while循环语句

实例2.1 循环输出1到10的数字

复制代码 代码如下:

#!/bin/bash
myvar=1
while [ $myvar
-le 10 ]
do
        echo $myvar
        myvar=$(( $myvar + 1
))
done

只要特定条件为真,”while” 语句就会执行

三、until循环语句

实例3.1 循环输出1到10的数字
“Until” 语句提供了与
“while” 语句相反的功能:只要特定条件为假,它们就重复。下面是一个与前面的 “while” 循环具有同等功能的 “until” 循环。

复制代码 代码如下:

#!/bin/bash
myvar=1
until [ $myvar
-gt 10 ]
do
        echo $myvar
       myvar=$(( $myvar + 1
))
done

Linux
Shell中写循环时,常常要用到变量的自增,现在总结一下整型变量自增的方法。
我所知道的,bash中,变量自增,目前有五种方法:
1.
i=`expr $i + 1`;
2. let i+=1;
3. ((i++));
4. i=$[$i+1];
5. i=$(( $i
+ 1 ))
可以实践一下,简单的实例如下:

#!/bin/bash
i=0;while [ $i -lt 4 
];do      echo $i;      i=`expr $i + 1`;      # let 
i+=1;      # ((i++));      # i=$[$i+1];      # i=$(( $i + 1 
))done

课后作业:

1.求100以内所有正整数之和

blob.png

2.编写脚本,通过ping命令探测10.1.252.1-254范围内的所有主机的在线状态,统计在线主机和离线主机各多少。

结果:

#!/bin/bash
  ip=1
  up=0 down=0
 ipv4=10.1.252 
until [ $n -gt 255  ]
do
IP="$ipv4"."$n"
#for ipv in {0..255} ;do
 #  IP="$ipv4"."$ipv"
let n++
   ping "$IP" -c 1 -W 1 &>/dev/null && echo "The Up IPv4 is:$IP" && let up+=1 &>/dev/null || let down+=1 &>/dev/null
done
 echo "IPv4($ipv4.1-255) up is :$up"
 echo "IPv4($ipv4.1-255) down is :$down"

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

代码:

#/bin/bash
i=1
j=1
until (($i>=10))
do
j=1
until (($j>$i))
do
sum=$[ $j*$i ]
echo -ne "$i*$j=$sum \t"
if [ $i == $j ] ;then
echo -en "\n"
      fi
     let j++
done
     let i++
done

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


#!/bin/bash
i=0
while (( i<10 ));do
    array[$i]=$((RANDOM%100))
  echo  -n "  ${array[$i]}"
 let i++
done
echo
max=${array[0]}
for j in `seq 1 9`;do
   if [ $max -lt ${array[$j]} ];then
     max=${array[$j]}
    else
   fi
done
echo $ma

x

5.编写脚本,实现打印国际象棋棋盘

~                                                                                                                      

#!/bin/bash
let i=0
let j=0
for ((i=0; i < 8; i++));do
    echo -n $i
     for((j=0; j < 8; j++));do
        if [ $[$[$i+$j]%2]  -eq 0 ];then
                echo -en  "\033[43m  \033[0m"
         else
                echo  -en  "\033[42m  \033[0m"
           fi
      done
     echo  
done
echo -e " "  {A..H}
~

blob.png                                                                       

~                                                                                                                                                                                              

6.打印等腰三角形     

#!/bin/bash
 for i in `seq 1 2 10`;do
        k=1
       while [ $k -le $((10-$(($i+1))/2)) ];do
          echo -ne " " 
          let k++
        done
       for j in `seq 1 $i`;do
          echo -n "*"
       done
      echo  
 done
#!/bin/bash
i=1
while [ $i -le 10 ] ; do
     j=1
     while [ $j -le $((10-$i)) ] ; do
        echo -n ' '
        j=$(($j+1))
     done
     j=1
    while [ $j -le $((2*$i-1)) ] ; do
      echo -n x
      j=$(($j+1))
     done
    echo
    i=$(($i+1))

7.猜数字游戏


#!/bin/bash
s=0
I=3
while (( $s == 0 ));do
    var=$((RANDOM%11))
    echo "welcome! you will have three times to guess a number in range 0 to 10!" 
    while (( $I != 0 ));do
         read -p " please input you guess number:"  guess
         if  [ $guess-ge 0 ]  &> /dev/null;then
           if [ $guess -lt $var ];then
               echo "you guess number is too little, you have $[$I-1] time to try "
           elif [ $guess -gt $var ];then
                echo " you gues number is too large,  you have $[$I-1] time to try"
            elif [ $guess -eq $var ];then
                echo -e  "\033[32moh,great! you are win\033[0m"
                read -p "do you want to continue ?, anykey to continue ,n to quit :"  c
                if [ $c == n ];then
                   echo "you have quit game,goodbye!"
                   exit
                else
                   echo "you will comtinue , good luck to yoiu"
                   s=0
                   I=3
                 continue 3
               fi
           fi
        else
           echo " you input is wrong,please again"
           continue
        fi
      let I--
  done
  if [ $I==0 ];then
       echo -e  "\033[31moh,sorry,you lose!\033[0m"
  fi
   read -p "do you want to continue ?, anykey to continue ,n to quit :"  c
         if [ $c == n ];then
             echo "you have quit game,goodbye!"
              s=1
          else
               echo "you will comtinue , good luck to yoiu"
                s=0
                I=3
          fi
done

原创文章,作者:zsyzgw,如若转载,请注明出处:http://www.178linux.com/37050

(0)
zsyzgwzsyzgw
上一篇 2016-08-22 09:29
下一篇 2016-08-22 09:29

相关推荐

  • Linux 第三天: (07月26日) Linux使用帮助

    Linux 第三天: (07月26日) Linux使用帮助         whatis 显示命令的简短描述makewhatis centos6 制作数据库mandb centos7 制作数据库 help COMMAND 内部命令man bash 内部命令COMMAND –help -h 外部命令man C…

    Linux干货 2016-08-08
  • LVM——如何让你的磁盘空间可大可小

    逻辑卷管理器(LVM) 允许对卷进行方便操作的抽象层,包括重新设定文件系统的大小 允许在多个物理设备间重新组织文件系统          将设备指定为物理卷          用一个或者多个物理卷来创…

    Linux干货 2016-08-29
  • iptables实战笔记一

    iptables实战 1.开启防火墙 systemctl start firewalld 2.清空所有的默认规则,我们自己定义自己的规则 iptables -F 查看此时的iptables iptables -nL Chain INPUT (policy ACCEPT) target prot opt source destination Chain FOR…

    Linux干货 2017-06-13
  • Linux的命令使用格式

    ◆Linux命令格式:command [options]  [arguments]command:命令options:  –单词   或   -单字如: ls –allequ      ls -als -a -b -cequ&…

    Linux干货 2016-10-31
  • 马哥教育网络班20期-第三周课程作业

    Table of Contents 1、列出当前系统上所有已经登录的用户的用户名,注意:同一个用户登录多次,则只显示一次即可。 2、取出最后登录到当前系统的用户的相关信息。 3、取出当前系统上被用户当作其默认shell的最多的那个shell。 4、将/etc/passwd中的第三个字段数值最大的后10个用户的信息全部改为大写后保存至/tmp/maxusers…

    Linux干货 2016-06-26
  • shell脚本的各种循环

    For循环 For循环格式      For   变量名  in    列表    ;   do         &nb…

    Linux干货 2016-08-21