首页 > 代码库 > Bash之for循环
Bash之for循环
示例:
格式: for 变量名 in 取值列表
do
命令序列
done
vim a.sh
#!/bin/bash
for A in "192.168.154.176" "192.168.1.2" "192.168.1.3"
do
if ping -c 3 $A &> /dev/null
then
echo "Host $A is up " >> /root/a.txt
else
echo "Host $A is down" >> /root/a.txt
fi
done
[root@master ~]# chmod +x a.sh
[root@master ~]# ./a.sh
[root@master ~]# cat a.txt
Host 192.168.154.176 is up
Host 192.168.1.2 is down
Host 192.168.1.3 is down
关于for循环取值列表的方式:
1)可以事先把列表写入文件中,然后再读取文件
2)使用seq命令定义,以上的脚本可以这样写:
#!/bin/bash
for A in `seq 156 160`
do
B="192.168.154.$A"
if ping -c 3 $B &> /dev/null
then
echo "Host $B is up " >> /root/a.txt
else
echo "Host $B is down" >> /root/a.txt
fi
done
3)使用大括号扩展,如:
#!/bin/bash
for A in {156..160}
do
B="192.168.154.$A"
if ping -c 3 $B &> /dev/null
then
echo "Host $B is up " >> /root/a.txt
else
echo "Host $B is down" >> /root/a.txt
fi
done
当然也可以使用双引号把各个元素隔离,像本文开始的示例。
本文出自 “一万年太久,只争朝夕” 博客,请务必保留此出处http://zengwj1949.blog.51cto.com/10747365/1918590
Bash之for循环