Unix : Shell script that monitors the system’s CPU usage and free memory

Shell Scripting @ Freshers.in

Here we will discuss on a shell script that monitors the system’s CPU usage and free memory, and issues a warning if either exceeds certain thresholds. This is a simplified system monitoring script:

Shell script:

#!/bin/bash

# Define thresholds
CPU_THRESHOLD=75
MEM_THRESHOLD=20

# Check CPU Usage
CPU_USAGE=$(top -b -n1 | grep "Cpu(s)" | awk '{print $2 + $4}')
CPU_USAGE=${CPU_USAGE%.*}

# Check Free Memory
FREE_MEM=$(free -m | awk 'NR==2{printf "%.2f", $4*100/$2 }')
FREE_MEM=${FREE_MEM%.*}

# CPU Usage alert
if [ "$CPU_USAGE" -gt "$CPU_THRESHOLD" ]
then
    echo "High CPU usage: ${CPU_USAGE}%"
fi

# Free Memory alert
if [ "$FREE_MEM" -lt "$MEM_THRESHOLD" ]
then
    echo "Low memory: Available memory is ${FREE_MEM}%"
fi

Here is what the script does, step by step:

  1. We define the thresholds for CPU usage and free memory at the beginning of the script. In this case, the CPU usage threshold is 75% and the free memory threshold is 20%.
  2. We use the top command to get CPU usage. The top -b -n1 command gets the first iteration of top stats in batch mode. We then extract the CPU line with grep, and use awk to add the user and system CPU percentages (fields 2 and 4). The result is stored in CPU_USAGE.
  3. We use the free command to get the free memory. The free -m command shows the amount of free and used memory in the system. We use awk to calculate the percentage of free memory. The result is stored in FREE_MEM.
  4. The script then checks if the CPU usage is greater than the threshold. If it is, it echoes a warning message.
  5. Similarly, the script checks if the percentage of free memory is less than the threshold. If it is, it echoes a warning message.

Other urls to refer

Author: user

Leave a Reply