课时8 使用for循环
一、for语句结构
语法格式
for 变量名
in 取值列表
do
命令序列
done
二、基本用法示范
示例1:一次输出3个字符串
[
root@localhost ~]# cat test1.sh
#!/bin/bash
for i in "1st." "2st." "3st."
do
echo $i
done
[
root@localhost ~]# ./test1.sh
2st.
3st.
示例2:逐词输出/etc/host.conf文件内容
[
root@localhost ~]# cat
/etc/host.conf
order hosts.bind
[
root@localhost ~]# cat test2.sh
#!/bin/bash
for i in $(cat /etc/host.conf)
do
echo $i
done
[
root@localhost ~]# ./test2.sh
hosts.bind
三、案例实战
案例实战一:批量加用户账号
1、用户列表文件users.txt,每行一个
2、将初始口令设为123456,首次登陆后必须更改
[
root@localhost ~]# cat
/root/users.txt
zhangsan
lisi
......
#!/bin/bash
for i in $(cat /root/users.txt)
do
useradd $i
echo "123456" | passwd --stdin $i
chage -d 0 $i
done
[
root@localhost ~]# ./uad.sh
Changing password for user zhangsan.
passwd: all authentication tokens updated successfully.
Changing password for user lisi.
passwd: all authentication tokens updated successfully.
......
[
root@localhost ~]# tail /etc/passwd
zhangsan:x:506:506::/home/zhangsan:/bin/bash
lisi:x:506:506::/home/llisi:/bin/bash
......
案例实战二:检测一个IP范围的主机状态
1、192.168.4.1 - 192.168.4.10
2、根据是否ping通来判断
#!/bin/bash
IP_PRE="192.168.4."
for i in $(seq 1 10)
do
ping -c 3 -i 0.2 -W 3 ${
IP_PRE
}$IP &> /dev/null
if [ $? -eq 0 ] ; then
echo "
${
IP_PRE
}$IP is up.
"
else
echo "
${
IP_PRE
}$IP is down.
"
fi
done
192.168.4.1 is up.
192.168.4.2 is up.
192.168.4.3 is up.
192.168.4.4 is down.
......