Shell脚本-while循环应用案例

97 阅读2分钟

在Shell脚本编程中,while循环是一种非常有用的控制结构,适用于需要基于条件进行重复操作的场景。与for循环不同,while循环通常用于处理不确定次数的迭代或持续监控某些状态直到满足特定条件为止的任务。本文将通过几个实际的应用案例来展示如何使用while循环解决具体的编程问题。

案例一:监控服务器资源使用情况

假设我们需要编写一个脚本来实时监控服务器的CPU和内存使用率,并在任一项超过设定阈值时发送警告信息。

脚本示例:

#!/bin/bash

cpu_threshold=80
mem_threshold=75

echo "Monitoring CPU and Memory usage..."

while true; do
    cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}') # 获取CPU使用率
    mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}') # 获取内存使用率
    
    if (( $(echo "$cpu_usage > $cpu_threshold" | bc -l) )); then
        echo "Warning: CPU usage is above threshold at $cpu_usage%"
    fi

    if (( $(echo "$mem_usage > $mem_threshold" | bc -l) )); then
        echo "Warning: Memory usage is above threshold at $mem_usage%"
    fi
    
    sleep 5 # 每隔5秒检查一次
done

说明:

  • 使用top命令获取CPU使用率,free命令获取内存使用率。
  • bc -l用于执行浮点数比较。
  • 通过sleep 5让脚本每隔5秒检查一次系统状态。

案例二:读取文件并处理每一行

假设我们有一个包含多个URL的文本文件,需要对每个URL发起HTTP请求以检查其可访问性。

脚本示例:

#!/bin/bash

input_file="urls.txt"

while IFS= read -r url
do
    if curl --output /dev/null --silent --head --fail "$url"; then
        echo "$url is up"
    else
        echo "$url is down"
    fi
done < "$input_file"

说明:

  • 使用IFS=防止行首尾的空白被忽略。
  • curl --output /dev/null --silent --head --fail用于检测URL是否可访问。
  • < "$input_file"将文件内容作为输入传递给read命令。

案例三:用户交互式菜单

创建一个简单的用户交互式菜单,允许用户选择不同的操作直到他们选择退出。

脚本示例:

#!/bin/bash

while true; do
    echo "Menu:"
    echo "1) Display current date and time"
    echo "2) List files in current directory"
    echo "3) Exit"
    read -p "Please enter your choice [1-3]:" choice

    case $choice in
        1)
            date
            ;;
        2)
            ls
            ;;
        3)
            echo "Exiting..."
            break
            ;;
        *)
            echo "Invalid option, please try again."
            ;;
    esac
done

说明:

  • read -p提示用户输入选项。
  • 使用case语句根据用户的选择执行相应的操作。
  • break用于退出无限循环。

案例四:批量重命名文件

假设我们有一组文件名不符合规范,需要对其进行批量重命名。

脚本示例:

#!/bin/bash

prefix="new_"

ls | while read -r file; do
    if [[ $file != ${prefix}* ]]; then
        mv "$file" "${prefix}${file}"
        echo "Renamed '$file' to '${prefix}${file}'"
    fi
done

说明:

  • 使用ls列出当前目录下的所有文件。
  • if [[ $file != ${prefix}* ]]确保只重命名不带前缀的文件。
  • mv "$file" "${prefix}${file}"添加指定前缀并重命名文件。

结语

感谢您的阅读!如果你有任何疑问或想要分享的经验,请在评论区留言交流!