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