欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Shell腳本之while循環(huán)應用具體案例

 更新時間:2025年04月28日 09:02:27   作者:難釋懷  
這篇文章主要介紹了Shell腳本之while循環(huán)應用的相關資料,通過四個案例展示了如何利用while循環(huán)來處理不同場景下的編程問題,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

前言

在Shell腳本編程中,while循環(huán)是一種非常有用的控制結構,適用于需要基于條件進行重復操作的場景。與for循環(huán)不同,while循環(huán)通常用于處理不確定次數(shù)的迭代或持續(xù)監(jiān)控某些狀態(tài)直到滿足特定條件為止的任務。本文將通過幾個實際的應用案例來展示如何使用while循環(huán)解決具體的編程問題。

案例一:監(jiān)控服務器資源使用情況

假設我們需要編寫一個腳本來實時監(jiān)控服務器的CPU和內(nèi)存使用率,并在任一項超過設定閾值時發(fā)送警告信息。

腳本示例:

#!/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}') # 獲取內(nèi)存使用率
    
    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命令獲取內(nèi)存使用率。
  • bc -l用于執(zhí)行浮點數(shù)比較。
  • 通過sleep 5讓腳本每隔5秒檢查一次系統(tǒng)狀態(tài)。

案例二:讀取文件并處理每一行

假設我們有一個包含多個URL的文本文件,需要對每個URL發(fā)起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"將文件內(nèi)容作為輸入傳遞給read命令。

案例三:用戶交互式菜單

創(chuàng)建一個簡單的用戶交互式菜單,允許用戶選擇不同的操作直到他們選擇退出。

腳本示例:

#!/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語句根據(jù)用戶的選擇執(zhí)行相應的操作。
  • break用于退出無限循環(huán)。

案例四:批量重命名文件

假設我們有一組文件名不符合規(guī)范,需要對其進行批量重命名。

腳本示例:

#!/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循環(huán)應用的文章就介紹到這了,更多相關Shell腳本while循環(huán)案例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論