SoFunction
Updated on 2025-04-28

Specific cases of while loop application of shell scripts

Preface

In Shell scripting,whileLooping is a very useful control structure suitable for scenarios where repeated operations are required based on conditions. andforThe cycle is different,whileLoops are often used to handle an iteration of uncertain times or to continuously monitor certain states until a specific condition is met. This article will show how to use it through several practical application caseswhileLooping to solve specific programming problems.

Case 1: Monitoring server resource usage

Suppose we need to write a script to monitor the server's CPU and memory usage in real time and send warning messages when either one exceeds the set threshold.

Script example:

#!/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}') # Get CPU usage    mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}') # Get memory usage    
    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 # Check every 5 secondsdone

illustrate:

  • usetopCommand to get CPU usage,freeCommand gets memory usage.
  • bc -lUsed to perform floating point comparisons.
  • passsleep 5Let the script check the system status every 5 seconds.

Case 2: Read the file and process each line

Suppose we have a text file with multiple URLs and we need to initiate an HTTP request for each URL to check its accessibility.

Script example:

#!/bin/bash

input_file=""

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"

illustrate:

  • useIFS=Prevent blanks at the beginning and end of the line from the front to the end of the line from the line from the line from the line from the line to be ignored.
  • curl --output /dev/null --silent --head --failUsed to detect whether the URL is accessible.
  • < "$input_file"Pass the file contents as input toreadOrder.

Case 3: User interactive menu

Create a simple user interactive menu that allows users to select different actions until they choose to exit.

Script example:

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

illustrate:

  • read -pPrompt the user to enter options.
  • usecaseThe statement performs corresponding operations according to the user's choice.
  • breakUsed to exit the infinite loop.

Case 4: Batch renaming files

Suppose we have a set of file names that do not comply with the specification and need to be renamed in batches.

Script example:

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

illustrate:

  • uselsLists all files in the current directory.
  • if [[ $file != ${prefix}* ]]Make sure to rename only files without prefixes.
  • mv "$file" "${prefix}${file}"Add the specified prefix and rename the file.

Conclusion

This is the end of this article about the while loop application of Shell scripts. For more relevant shell scripts while loop cases, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!