一、for 循环(最常用)
1. 循环数字 1~10
bash
运行
for i in {1..10}; do
echo "数字:$i"
done
2. 循环某个目录下的所有文件
bash
运行
for file in /tmp/*; do
echo "文件:$file"
done
3. 循环列表(比如用户名、IP)
bash
运行
for user in tom jack lily; do
echo "用户:$user"
done
4. 类 C 语言风格的 for(运维常用)
bash
运行
for ((i=1; i<=5; i++)); do
echo "计数:$i"
done
二、while 循环
1. 最基础 while
bash
运行
i=1
while [ $i -le 5 ]; do
echo "while 计数:$i"
i=$((i+1))
done
2. 读文件每一行(超级常用)
bash
运行
while read line; do
echo "内容:$line"
done < ip.txt
3. 死循环(用来监控、等待)
bash
运行
while true; do
echo "正在监控..."
sleep 1
done
三、实战脚本(直接拿去用)
实战 1:批量创建 10 个文件
bash
运行
for i in {1..10}; do
touch test_$i.txt
done
实战 2:批量 ping 一批 IP
bash
运行
cat > ip.txt << EOF
192.168.1.1
192.168.1.2
192.168.1.3
EOF
while read ip; do
ping -c 2 $ip > /dev/null
if [ $? -eq 0 ]; then
echo "$ip 通"
else
echo "$ip 不通"
fi
done < ip.txt
实战 3:循环检查某个服务是否启动
bash
运行
while true; do
if pgrep nginx > /dev/null; then
echo "nginx 运行中"
break
else
echo "等待 nginx 启动..."
sleep 2
fi
done