Shell脚本-while循环应用案例
在Shell脚本编程中,while
循环是一种非常有用的控制结构,适用于需要基于条件进行重复操作的场景。与for
循环不同,while
循环通常用于处理不确定次数的迭代或持续监控某些状态直到满足特定条件为止的任务。本文将通过几个实际的应用案例来展示如何使用while
循环解决具体的编程问题。
案例一:监控服务器资源使用情况
假设我们需要编写一个脚本来实时监控服务器的CPU和内存使用率,并在任一项超过设定阈值时发送警告信息。
脚本示例:
#!/bin/bashcpu_threshold=80
mem_threshold=75echo "Monitoring CPU and Memory usage..."while true; docpu_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) )); thenecho "Warning: CPU usage is above threshold at $cpu_usage%"fiif (( $(echo "$mem_usage > $mem_threshold" | bc -l) )); thenecho "Warning: Memory usage is above threshold at $mem_usage%"fisleep 5 # 每隔5秒检查一次
done
说明:
- 使用
top
命令获取CPU使用率,free
命令获取内存使用率。 bc -l
用于执行浮点数比较。- 通过
sleep 5
让脚本每隔5秒检查一次系统状态。
案例二:读取文件并处理每一行
假设我们有一个包含多个URL的文本文件,需要对每个URL发起HTTP请求以检查其可访问性。
脚本示例:
#!/bin/bashinput_file="urls.txt"while IFS= read -r url
doif curl --output /dev/null --silent --head --fail "$url"; thenecho "$url is up"elseecho "$url is down"fi
done < "$input_file"
说明:
- 使用
IFS=
防止行首尾的空白被忽略。 curl --output /dev/null --silent --head --fail
用于检测URL是否可访问。< "$input_file"
将文件内容作为输入传递给read
命令。
案例三:用户交互式菜单
创建一个简单的用户交互式菜单,允许用户选择不同的操作直到他们选择退出。
脚本示例:
#!/bin/bashwhile true; doecho "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]:" choicecase $choice in1)date;;2)ls;;3)echo "Exiting..."break;;*)echo "Invalid option, please try again.";;esac
done
说明:
read -p
提示用户输入选项。- 使用
case
语句根据用户的选择执行相应的操作。 break
用于退出无限循环。
案例四:批量重命名文件
假设我们有一组文件名不符合规范,需要对其进行批量重命名。
脚本示例:
#!/bin/bashprefix="new_"ls | while read -r file; doif [[ $file != ${prefix}* ]]; thenmv "$file" "${prefix}${file}"echo "Renamed '$file' to '${prefix}${file}'"fi
done
说明:
- 使用
ls
列出当前目录下的所有文件。 if [[ $file != ${prefix}* ]]
确保只重命名不带前缀的文件。mv "$file" "${prefix}${file}"
添加指定前缀并重命名文件。
结语
感谢您的阅读!如果你有任何疑问或想要分享的经验,请在评论区留言交流!