for循环的语法:
1. for 变量 in 值1 值2 值3....
do
程序
done
例如:下列脚本会分别打印4次 分别是morning noon afternoon evening的值
1 #!/bin/bash 2 #打印时间 3 #Author Mrfeng 4 5 for time in morning noon afternoon evening 6 do 7 echo $time 8 done
例如批量解压缩:
1 #!/bin/bash 2 #批量解压缩脚本 3 #Author: Mrf 4 5 path=/opt/lamp 6 7 cd $path 8 9 ls *.tar.gz > ls.log 10 ls *.tgz >> ls.log 11 for i in $(cat ls.log) 12 do 13 tar zxvf $i &>>cc.log 14 done 15 rm -rf ls.log
2.for 语法二
格式:
1 for ((初始值;循环控制条件;变量变化)) 2 do 3 程序 4 done
例如:
1 #!/bin/bash 2 #从1加到100 3 4 s=0 5 for(( i=1;i<=100;i=i+1 )) 6 do 7 s=$(($s+$i)) 8 done 9 echo "the sum of 1+2+...+100is: $s"
例如:批量添加用户
1 #!/bin/bash 2 # 批量添加用户数量的用户 3 # Author:Mr f (E-mail:22222222) 4 5 read -p "Please input user name:" -t 30 name 6 read -p "Please input the number of users:" -t 30 num 7 read -p "Please input the password of users:" -t 30 pass 8 if [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ] 9 then 10 y=$(echo $num | sed ‘s/[0-9]//g‘) 11 if [ -z "$y" ] ; then 12 for ((i=1;i<=$num;i=i+1)) 13 do 14 /usr/sbin/useradd $name$i &>/dev/null 15 echo $pass | /usr/bin/passwd --stdin $n 16 ame$i &>/dev/null 17 done 18 fi 19 fi 20 cat /etc/passwd | grep user[1-$num] | cut -d ":" -f 1 >>userlist.log
当然我也写了一个利用 userlist.log进行批量删除的脚本方便大家做完实验后清理
1 #!/bin/bash 2 for i in $(cat ./userlist.log) 3 do 4 /usr/sbin/userdel -r $i &>>del.log 5 done 6 #cat del.log 7 rm -rf del.log
时间: 2024-10-19 09:12:57