(34)for循环

时间:2022-07-24
本文章向大家介绍(34)for循环,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

格式1:

for 变量 in 值1 值2 值3
do
程序
done

例1.打印时间

脚本内容

#!/bin/bash
#Author:yuzai
for time in morning noon afternoon evening
  do
    echo “This time is $time!”
  done

脚本执行结果

[root@lhh98330]# chmod 755 test4.sh 
[root@llhh98330]# ./test4.sh 
“This time is morning!”
“This time is noon!”
“This time is afternoon!”
“This time is evening!”

PS.这种方法看起来很笨,需要把循环次数写入for,但是在系统管理的时候,当我们不确定循环次数的时候(如下面的例子),这个时候这种方法就有一种好处,循环变量只要是由空格、回车、制表符分隔的(和cat,ls等命令结合使用,cat命令执行之后显示的结果就是由回车隔开的)。

例2.批量解压缩(不知道循环次数)

#!/bin/bash
#Author:yuzai
ls *.tar.gz > ls.log  #将所有以.tar.gz结尾的文件输出覆盖到ls.log文件
for i in $(cat ls.log)
        do
        tar -zxf $i $>/dev/null
        done
rm -rf /lamp/ls.log

例3.计算文件个数(不知道循环次数)

#!/bin/bash
#Author:yuzai
cd /root/sh
ls *.sh > ls.log
y=1
for i in $(cat ls.log)
        do
        echo $y
        y=$(($y+1))
        done
rm -rf ls.log

格式2:

for ((初始值;循环控制条件;变量变化))
do
程序
done

例1.从1加到100(知道循环次数)

#!/bin/bash
#Author:yuzai
s=0
for ((i=1;i<=100;i=i+1))
        do
                s=$(($s+$i))
        done
echo "The sum of 1+2+...+99+100 is $s!"

例2.批量创建用户

#!/bin/bash
#Author:yuzai
read -p "Please input user name: " -t 30 name   #输入用户名,等待时间30s
read -p "Please input the number of users: " -t 30 num  #输入创建用户个数,等待时间30s
read -p "Please input the password of users: " -t 30 pass       #输入用户密码,等待时间30s
if [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ]      #判断输入信息是否为空 
then
    y=$(echo $num | sed s/'^[0-9]*$'//g)    #这里是判断输入的用户个数是否为数字,sed后也可以把^[0-9]*$换为's/[0-9]//g'
    if [ -z "$y" ]  #如果上一条语句输出不为空,就是输入的用户个数为数字,继续执行
    then
     for ((i=1;i<=$num;i=i+1)) #开始循环
       do
          /usr/sbin/useradd "$name$i" &>/dev/null #建立用户
           echo $pass | /usr/bin/passwd --stdin "$name$i" &>/dev/null      #设置用户密码,与用户名相同
             done
     fi
fi 

执行结果:

[root@laptop]# chmod 755 3.sh 
[root@laptop]# ./3.sh 
Please input user name: new
Please input the number of users: 3
Please input the password of users: 111
[root@laptop]# cat /etc/passwd
new1:x:1006:1008::/home/new1:/bin/bash
new2:x:1007:1009::/home/new2:/bin/bash
new3:x:1008:1010::/home/new3:/bin/bash

END