Monitoring RAM Space, Disk Space, and CPU Usage with a Bash Script in Linux

Monitoring RAM Space, Disk Space, and CPU Usage with a Bash Script in Linux

Introduction

As a system administrator or developer, keeping an eye on resource utilization is essential.

In this article, we’ll explore how to monitor RAM, disk space, and CPU usage using a straightforward Bash script on a Linux operating system.

Prerequisites

Before we dive into the script, ensure you have the following:

1. A Linux distribution (any flavor will do)

2. Basic knowledge of Bash scripting

The Bash Script

Below is a basic Bash script that continuously monitors CPU and memory usage. Feel free to customize it according to your specific requirements:

#!/bin/bash

while :

do

# Get memory usage
memUsage=$(free -m | awk '/Mem/{print $3}')
totalMem=$(free -m | awk '/Mem/{print $2}')

# Get disk usage
diskUsage=$(df -h | awk '$NF=="/"{print $3}')
totalDisk=$(df -h | awk '$NF=="/"{print $2}')

# Get CPU load
cpuLoad=$(uptime | awk -F'[a-z]:' '{ print $2 }')

# Print the usage
echo "Memory Usage: $memUsage MB / $totalMem MB ($(bc <<< "scale=2; $memUsage*100/$totalMem"))%"
echo "Disk Usage: $diskUsage / $totalDisk ($(df -h | awk '$NF=="/"{print $5}'))"
echo "CPU Load: $cpuLoad"

# Sleep for 3 second
sleep 3

done        

Explanation

1. The script uses the top command to retrieve CPU usage and the free command to get memory usage.

2. It prints the results to the console.

3. The sleep 3 line ensures that the script runs continuously with a 3-second interval.

Customization

You can enhance this script by:

1. Adding disk space monitoring using the df command.

2. Setting thresholds for alerts when usage exceeds a certain percentage.

3. Redirecting output to a log file for historical analysis.

Conclusion

With this simple Bash script, you can keep track of your system’s performance in real time. Feel free to adapt and expand it to suit your specific needs. Happy monitoring! ??


Follow me Amar M. for more Updates


#innovation #management #digitalmarketing #technology #creativity #futurism #startups #marketing #entrepreneurship #leadership #business #productivity #networking #career #industry #Linux #Cloud #AWS #DevOps #SAP #LinuxServer

要查看或添加评论,请登录

社区洞察

其他会员也浏览了