第164集:循环语句

教学目标

  • 掌握Shell脚本中for循环的使用方法
  • 熟悉while循环和until循环的语法和应用场景
  • 学习循环控制语句(break、continue)的使用
  • 理解嵌套循环的概念和应用
  • 能够在脚本中使用循环语句实现重复执行的任务

主要知识点

  1. for循环的基本语法
  2. while循环的使用
  3. until循环的应用
  4. 循环控制语句
  5. 嵌套循环
  6. 循环的实际应用场景

实用案例分析

案例1:基本for循环

目标:学习使用基本的for循环遍历列表和范围。

操作步骤

  1. 创建基本for循环演示脚本
# 创建脚本文件
touch basic-for.sh

# 编辑脚本文件
vim basic-for.sh

# 添加以下内容
#!/bin/bash
# 演示基本for循环

# 1. 遍历列表
echo "=== Looping through a list ==="
for fruit in apple banana cherry date;
do
    echo "I like $fruit"
done

# 2. 遍历数字范围
echo "\n=== Looping through a number range ==="
for i in {1..5};
do
    echo "Number: $i"
done

# 3. 使用seq命令生成序列
echo "\n=== Using seq command ==="
for i in $(seq 1 2 10);
do
    echo "Odd number: $i"
done

# 4. 遍历命令输出
echo "\n=== Looping through command output ==="
echo "Files in current directory:"
for file in $(ls -la | grep "^-");
do
    echo $file
done

# 5. 遍历数组
echo "\n=== Looping through an array ==="
fruits=(apple banana cherry date)
for fruit in "${fruits[@]}";
do
    echo "Fruit: $fruit"
done
  1. 运行脚本并查看结果
# 设置执行权限
chmod +x basic-for.sh

# 运行脚本
./basic-for.sh

案例2:C风格for循环

目标:学习使用C风格的for循环。

操作步骤

  1. 创建C风格for循环演示脚本
# 创建脚本文件
touch c-style-for.sh

# 编辑脚本文件
vim c-style-for.sh

# 添加以下内容
#!/bin/bash
# 演示C风格for循环

# 1. 基本C风格for循环
echo "=== Basic C-style for loop ==="
for ((i=1; i<=5; i++));
do
    echo "Iteration: $i"
done

# 2. 使用不同的步长
echo "\n=== For loop with different step ==="
for ((i=10; i>=1; i-=2));
do
    echo "Countdown: $i"
done

# 3. 嵌套C风格for循环
echo "\n=== Nested C-style for loops ==="
for ((i=1; i<=3; i++));
do
    for ((j=1; j<=3; j++));
    do
        echo "i=$i, j=$j"
    done
done

# 4. 使用循环计算
echo "\n=== Using loop for calculation ==="
sum=0
for ((i=1; i<=100; i++));
do
    sum=$((sum + i))
done
echo "Sum of 1 to 100: $sum"

# 5. 无限循环(按Ctrl+C退出)
echo "\n=== Infinite loop (press Ctrl+C to exit) ==="
for ((;;));
do
    echo "This is an infinite loop"
    sleep 1
done
  1. 运行脚本并查看结果
# 设置执行权限
chmod +x c-style-for.sh

# 运行脚本
./c-style-for.sh

案例3:while循环

目标:学习使用while循环进行条件判断和循环执行。

操作步骤

  1. 创建while循环演示脚本
# 创建脚本文件
touch while-loop.sh

# 编辑脚本文件
vim while-loop.sh

# 添加以下内容
#!/bin/bash
# 演示while循环

# 1. 基本while循环
echo "=== Basic while loop ==="
counter=1
while [ $counter -le 5 ]; do
    echo "Counter: $counter"
    counter=$((counter + 1))
done

# 2. 使用while循环读取文件
echo "\n=== Reading file with while loop ==="
# 创建测试文件
echo "Line 1" > test.txt
echo "Line 2" >> test.txt
echo "Line 3" >> test.txt

# 读取文件内容
while read line; do
    echo "Read: $line"
done < test.txt

# 3. 使用while循环读取用户输入
echo "\n=== Reading user input with while loop ==="
echo "Enter text (type 'exit' to quit):"
while read input; do
    if [ "$input" = "exit" ]; then
        break
    fi
    echo "You entered: $input"
done

# 4. 无限while循环(按Ctrl+C退出)
echo "\n=== Infinite while loop (press Ctrl+C to exit) ==="
while true; do
    echo "This is an infinite loop"
    sleep 1
done
  1. 运行脚本并查看结果
# 设置执行权限
chmod +x while-loop.sh

# 运行脚本
./while-loop.sh

案例4:until循环

目标:学习使用until循环执行操作直到条件满足。

操作步骤

  1. 创建until循环演示脚本
# 创建脚本文件
touch until-loop.sh

# 编辑脚本文件
vim until-loop.sh

# 添加以下内容
#!/bin/bash
# 演示until循环

# 1. 基本until循环
echo "=== Basic until loop ==="
counter=1
until [ $counter -gt 5 ]; do
    echo "Counter: $counter"
    counter=$((counter + 1))
done

# 2. 使用until循环等待用户输入
echo "\n=== Waiting for correct input with until loop ==="
correct_password="secret"
read -s -p "Enter password: " password
echo

until [ "$password" = "$correct_password" ]; do
    echo "Incorrect password. Try again."
    read -s -p "Enter password: " password
    echo
done
echo "Correct password! Access granted."

# 3. 使用until循环检查服务状态
echo "\n=== Checking service status with until loop ==="
service_name="ssh"

# 模拟检查服务状态
attempt=1
until systemctl is-active --quiet $service_name || [ $attempt -gt 5 ]; do
    echo "Attempt $attempt: $service_name service is not active"
    attempt=$((attempt + 1))
    sleep 2
done

if systemctl is-active --quiet $service_name; then
    echo "$service_name service is now active"
else
    echo "Failed to start $service_name service after 5 attempts"
fi
  1. 运行脚本并查看结果
# 设置执行权限
chmod +x until-loop.sh

# 运行脚本
./until-loop.sh

案例5:循环控制语句

目标:学习使用break和continue语句控制循环的执行。

操作步骤

  1. 创建循环控制语句演示脚本
# 创建脚本文件
touch loop-control.sh

# 编辑脚本文件
vim loop-control.sh

# 添加以下内容
#!/bin/bash
# 演示循环控制语句

# 1. 使用break语句
echo "=== Using break statement ==="
for i in {1..10}; do
    if [ $i -eq 6 ]; then
        echo "Breaking loop at $i"
        break
    fi
    echo "Iteration: $i"
done

# 2. 使用continue语句
echo "\n=== Using continue statement ==="
for i in {1..10}; do
    if [ $((i % 2)) -eq 0 ]; then
        continue
    fi
    echo "Odd number: $i"
done

# 3. 在嵌套循环中使用break
echo "\n=== Using break in nested loops ==="
for i in {1..3}; do
    echo "Outer loop: $i"
    for j in {1..3}; do
        if [ $j -eq 2 ]; then
            echo "Breaking inner loop at j=$j"
            break
        fi
        echo "  Inner loop: $j"
    done
done

# 4. 使用标签和break跳出外层循环
echo "\n=== Using label with break ==="
outer_loop:
for i in {1..3}; do
    echo "Outer loop: $i"
    for j in {1..3}; do
        if [ $j -eq 2 ]; then
            echo "Breaking to outer loop at j=$j"
            break outer_loop
        fi
        echo "  Inner loop: $j"
    done
done

# 5. 综合使用循环控制语句
echo "\n=== Combining loop control statements ==="
for i in {1..10}; do
    if [ $i -lt 3 ]; then
        continue  # 跳过前2次迭代
    elif [ $i -gt 7 ]; then
        break  # 当i>7时跳出循环
    fi
    echo "Processing: $i"
done
  1. 运行脚本并查看结果
# 设置执行权限
chmod +x loop-control.sh

# 运行脚本
./loop-control.sh

案例6:循环的实际应用

目标:学习在实际场景中使用循环语句。

操作步骤

  1. 创建循环实际应用演示脚本
# 创建脚本文件
touch loop-practical.sh

# 编辑脚本文件
vim loop-practical.sh

# 添加以下内容
#!/bin/bash
# 演示循环的实际应用

# 1. 批量重命名文件
echo "=== Batch renaming files ==="
# 创建测试文件
for i in {1..5}; do
    touch file$i.txt
done

echo "Before renaming:"
ls -la file*.txt

# 批量重命名
counter=1
for file in file*.txt; do
    mv "$file" "document_$counter.txt"
    counter=$((counter + 1))
done

echo "\nAfter renaming:"
ls -la document_*.txt

# 2. 监控系统资源
echo "\n=== Monitoring system resources ==="
echo "Monitoring CPU usage for 5 seconds..."

for i in {1..5}; do
    cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
    echo "CPU usage: $cpu_usage%"
    sleep 1
done

# 3. 生成报告
echo "\n=== Generating report ==="
# 创建测试数据
> report.txt
echo "User Report" >> report.txt
echo "==========" >> report.txt

# 生成用户报告
users=$(who | awk '{print $1}' | sort | uniq)
for user in $users; do
    login_time=$(who | grep "$user" | awk '{print $4}')
    echo "User: $user, Login time: $login_time" >> report.txt
done

echo "Report generated:"
cat report.txt

# 4. 备份文件
echo "\n=== Backing up files ==="
# 创建备份目录
backup_dir="backup_$(date +%Y%m%d)"
mkdir -p $backup_dir

echo "Backing up .sh files..."
for file in *.sh; do
    if [ -f "$file" ]; then
        cp "$file" "$backup_dir/"
        echo "Backed up: $file"
    fi
done

echo "\nBackup completed. Files in backup directory:"
ls -la $backup_dir/
  1. 运行脚本并查看结果
# 设置执行权限
chmod +x loop-practical.sh

# 运行脚本
./loop-practical.sh

课后练习

  1. 基础练习

    • 创建一个脚本,使用for循环计算1到100的和
    • 编写一个脚本,使用while循环实现简单的倒计时功能
    • 设计一个脚本,使用until循环等待用户输入正确的密码
  2. 进阶练习

    • 创建一个脚本,使用嵌套循环生成九九乘法表
    • 编写一个脚本,使用循环遍历目录中的所有文件并统计文件类型
    • 设计一个脚本,使用循环监控系统内存使用情况并在超过阈值时发出警告
  3. 挑战练习

    • 编写一个脚本,使用循环实现简单的文件搜索功能
    • 创建一个脚本,使用循环批量处理图片文件(重命名、调整大小等)
    • 设计一个脚本,使用循环实现简单的网络端口扫描器

总结

本集详细介绍了Linux Shell脚本中的循环语句,包括for循环、while循环、until循环以及循环控制语句的使用方法。通过学习这些知识,读者可以在Shell脚本中实现重复执行的任务,提高脚本的自动化能力。

循环语句是Shell脚本编程中的重要组成部分,它允许脚本重复执行特定的代码块,从而处理大量的相似任务。掌握循环语句的使用是编写复杂Shell脚本的基础。

通过本集的学习,读者应该能够理解和使用基本的for循环、C风格for循环、while循环和until循环,掌握循环控制语句(break、continue)的使用方法,以及理解嵌套循环的概念和应用场景。这些知识将为后续学习函数定义和数组操作打下基础。

« 上一篇 条件判断 下一篇 » 函数定义