目录前言案例一:监控服务器资源使用情况
脚本示例:
案例二:读取文件并处理每一行
脚本示例:
案例三:用户交互式菜单
脚本示例:
案例四:批量重命名文件
脚本示例:
结语前言在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}"添加指定前缀并重命名文件。
结语到此这篇关于Shell脚本之while循环应用的文章就介绍到这了,更多相关Shell脚本while循环案例内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:Shell中的循环语句for、while、until实例讲解linux shell循环:for、while、until用法详解Shell中的for和while循环详细总结Shell中的while循环几种使用实例详解shell命令while循环中使用sleep命令代码示例Shell脚本while、until循环语句简明教程shell脚本实战-while循环语句linux shell常用循环与判断语句(for,while,until,if)使用方法Windows Powershell Do While 循环Shell循环语句的使用(for循环、while循环、until循环)
