1. 语法
for 变量 in 值1 值2 值3...
do
程序
done
或者
for ((初始值;循环控制条件;变量变化))
do
程序
done
2. 练习1:循环打印1-5
[root@catyuan ~]# vim for1.sh
#!/bin/bash
for i in 1 2 3 4 5
do
echo $i
done
测试脚本
[root@catyuan ~]# chmod 755 for1.sh
[root@catyuan ~]# ./for1.sh
1
2
3
4
5
3. 练习2:批量解压缩
数据准备:准备三个压缩文件
[root@catyuan ~]# mkdir /root/test/
[root@catyuan test]# tar -zcf /root/test/etc.tar.bz2 /etc/
[root@catyuan test]# tar -zcf /root/test/tmp.tar.gz /tmp/
[root@catyuan test]# tar -zcf /root/test/usr.tar.gz /usr/
[root@catyuan ~]# ls /root/test/
etc.tar.gz tmp.tar.gz usr.tar.gz
脚本
#!/bin/bash
#批量解压缩
cd /root/test #切换到解压文件存在的目录
ls *.tar.gz > ls.log #将目录下是压缩文件的文件写入ls.log这个文件中
for i in $( cat ls.log ) #通过for循环读取文件的内容,读取一次,执行一次程序
do
tar -zxf $i &> /dev/null
done
rm -rf ls.log #解压完成后,删掉日志文件,防止下次执行时造成干扰
测试脚本
[root@catyuan ~]# chmod 755 for2.sh
[root@catyuan ~]# ./for2.sh
[root@catyuan test]# ls
etc etc.tar.gz tmp tmp.tar.gz usr usr.tar.gz
4. 练习3:从1加到100
脚本
[root@catyuan ~]# vim for3.sh
#!/bin/bash
#从1加到100
s=0
for (( i=1;i<=100;i=i+1 )) #shell不支持i++
do
s=$(( $s+$i ))
done
echo "the sum of 1+2+...+100 is:$s"
测试脚本
[root@catyuan ~]# chmod 755 for3.sh
[root@catyuan ~]# ./for3.sh
the sum of 1+2+...+100 is:5050
5. 练习4:批量添加指定数量的用户
脚本
[root@catyuan ~]# vim for4.sh
#!/bin/bash
#批量添加指定数量的用户
read -p "please input user name:" -t 30 name #添加用户的名字
read -p "please input the number of users:" -t 30 num #添加用户的数量
read -p "please input the passwd of users:" -t 30 pass #添加用户的密码
if [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ];then #判断三个变量不为空,才会执行下面的命令
y=$(echo $num | sed 's/[0-9]//g') #把数字替换为空
if [ -z "$y" ];then #判断是否为空,可以判断出num中的值是否为纯数字
for (( i=1;i<=$num;i=i+1 )) #如果i<=num,则执行下面的程序
do
/usr/sbin/useradd $name$i &> /dev/null #添加用户
echo $pass | /usr/bin/passwd --stdin $name$i &> /dev/null #用户密码
done
fi
fi
测试脚本
[root@catyuan ~]# chmod 755 for4.sh
[root@catyuan ~]# ./for4.sh
please input user name:user
please input the number of users:3
please input the passwd of users:redhat
[root@catyuan ~]# cat /etc/passwd ##文件末尾出现下面三行
user1:x:1003:1003::/home/user1:/bin/bash
user2:x:1004:1004::/home/user1:/bin/bash
user3:x:1005:1005::/home/user1:/bin/bash