linux shell

关注公众号 jb51net

关闭
首页 > 脚本专栏 > linux shell > Shell脚本while循环案例

Shell脚本之while循环应用具体案例

作者:難釋懷

这篇文章主要介绍了Shell脚本之while循环应用的相关资料,通过四个案例展示了如何利用while循环来处理不同场景下的编程问题,文中通过代码介绍的非常详细,需要的朋友可以参考下

前言

在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

说明:

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

假设我们有一个包含多个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"

说明:

案例三:用户交互式菜单

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

脚本示例:

#!/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

说明:

案例四:批量重命名文件

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

脚本示例:

#!/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

说明:

结语

到此这篇关于Shell脚本之while循环应用的文章就介绍到这了,更多相关Shell脚本while循环案例内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文