Shell脚本 ——while循环
基本介绍: 在Shell脚本中,while 循环是一种用于重复执行命令的控制结构,直到给定的条件变为假为止。while 循环有几种不同的写法和使用方式,适用于各种场景。
基本格式:
while [ condition ]; do
# Commands to be executed
done
示例:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
输出:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
使用 (( )) 进行条件判断:
格式:
while (( condition )); do
# Commands to be executed
done
示例:
#!/bin/bash
count=1
while (( count <= 5 )); do
echo "Count: $count"
((count++))
done
输出:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
无限循环:
while :; do
# Commands to be executed
done
示例:
#!/bin/bash
count=1
while :; do
echo "Count: $count"
((count++))
if [ $count -gt 5 ]; then
break
fi
done
输出:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
读取文件中的每一行:
格式:
while IFS= read -r line; do
# Commands to be executed
done < "file.txt"
示例:
#!/bin/bash
while IFS= read -r line; do
echo "Line: $line"
done < "example.txt"
使用命令输出作为条件:
格式:
while command; do
# Commands to be executed
done
示例:
#!/bin/bash
while ping -c 1 google.com &> /dev/null; do
echo "Google is reachable"
sleep 1
done
示例Shell脚本: 以下是一个综合示例,展示了 while 循环的不同用法:
#!/bin/bash
# 基本格式
echo "Basic while loop:"
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
# 使用 (( )) 进行条件判断
echo "Using (( )) for condition:"
count=1
while (( count <= 5 )); do
echo "Count: $count"
((count++))
done
# 无限循环
echo "Infinite loop with break condition:"
count=1
while :; do
echo "Count: $count"
((count++))
if [ $count -gt 5 ]; then
break
fi
done
# 读取文件中的每一行
echo "Reading lines from a file:"
while IFS= read -r line; do
echo "Line: $line"
done < "example.txt"
# 使用命令输出作为条件
echo "Using command output as condition:"
while ping -c 1 google.com &> /dev/null; do
echo "Google is reachable"
sleep 1
done
注意点:
1、空格和引号: 在 while 循环中,确保条件和命令之间有适当的空格。对于包含空格或特殊字符的变量,使用引号。
2、文件读取: 使用 while 循环读取文件时,推荐使用 IFS= read -r 以防止读取时丢失空白字符和特殊字符。
3、无限循环: 在使用无限循环时,需要确保在适当的条件下退出循环,以避免进入死循环。
更多内容请参考 Shell 脚本专栏。