Monitor Linux System Resources with Simple Shell Scripts
This guide shows how to write Bash functions that retrieve process IDs, CPU, memory, file‑descriptor usage, port status, system load and disk space on a Linux server, and how to combine them with conditional checks to generate alerts when thresholds are exceeded.
Introduction
The article explains how to use shell scripts on Linux to monitor various system and process resources, providing reusable functions and example usage that can be integrated into automated alerting workflows.
Process ID Retrieval
The GetPID function accepts a user name and a process name, runs ps, filters with grep, and extracts the PID using sed and awk. Example:
function GetPID {
PsUser=$1
PsName=$2
pid=$(ps -u $PsUser | grep $PsName | grep -v grep | grep -v vi | grep -v dbx | grep -v tail | grep -v start | grep -v stop | sed -n 1p | awk '{print $1}')
echo $pid
}Calling PID=$(GetPID root CFTestApp) returns the PID (e.g., 11426), which can be verified with echo $PID.
CPU Usage Monitoring
The GetCpu function returns the integer part of a process’s CPU usage percentage:
function GetCpu {
CpuValue=$(ps -p $1 -o pcpu | grep -v CPU | awk '{print $1}' | awk -F. '{print $1}')
echo $CpuValue
}The CheckCpu wrapper compares the value against a threshold (default 80%) and prints an appropriate message:
function CheckCpu {
PID=$1
cpu=$(GetCpu $PID)
if [ $cpu -gt 80 ]; then
echo "The usage of cpu is larger than 80%"
else
echo "The usage of cpu is normal"
fi
}Example output shows a CPU usage of 75% and the normal‑status message.
Memory Usage Monitoring
The GetMem function obtains a process’s virtual memory size in megabytes:
function GetMem {
MEMUsage=$(ps -o vsz -p $1 | grep -v VSZ)
(( MEMUsage /= 1000 ))
echo $MEMUsage
}The surrounding logic in CheckMem (not explicitly named) compares the value against 1600 MB and reports normal or warning status. Example output shows 248 MB usage, which is normal.
File‑Descriptor (Handle) Monitoring
The GetDes function counts open file descriptors for a given PID:
function GetDes {
DES=$(ls /proc/$1/fd | wc -l)
echo $DES
}A threshold of 900 descriptors is used; the example shows 528 descriptors, indicating normal usage.
Port Listening Check
The Listening function determines whether a specified TCP or UDP port is listening by parsing netstat output:
function Listening {
TCPListeningnum=$(netstat -an | grep ":$1 " | awk '$1 == "tcp" && $NF == "LISTEN" {print $0}' | wc -l)
UDPListeningnum=$(netstat -an | grep ":$1 " | awk '$1 == "udp" && $NF == "0.0.0.0:*" {print $0}' | wc -l)
(( Listeningnum = TCPListeningnum + UDPListeningnum ))
if [ $Listeningnum -eq 0 ]; then
echo "0"
else
echo "1"
fi
}Running isListen=$(Listening 8080) and checking the result prints whether the port is listening.
System CPU Load Monitoring
The GetSysCPU function uses vmstat to compute average CPU idle time over five samples, then calculates the used CPU percentage:
function GetSysCPU {
CpuIdle=$(vmstat 1 5 | sed -n '3,$p' | awk '{x = x + $15} END {print x/5}' | awk -F. '{print $1}')
CpuNum=$(echo "100-$CpuIdle" | bc)
echo $CpuNum
}The script then alerts if usage exceeds 90%.
Disk Space Monitoring
The GetDiskSpc function reports the usage percentage of a specified directory using df:
function GetDiskSpc {
if [ $# -ne 1 ]; then return 1; fi
Folder=$1
DiskSpace=$(df -k | grep $Folder | awk '{print $5}' | awk -F% '{print $1}')
echo $DiskSpace
}Example checks /boot and reports 14% usage, which is normal.
Command Reference
ps : list processes; options -u, -p, -o.
grep : filter text; -v for inverse match.
sed : stream editor; -n to suppress automatic printing.
awk : pattern‑scanning language for text processing.
netstat : network statistics; -a, -n.
vmstat : virtual memory statistics.
df : disk free space.
Conclusion
Shell scripts provide a lightweight, flexible way to continuously monitor Linux system resources such as process existence, CPU, memory, file descriptors, ports, overall CPU load, and disk usage. By embedding threshold checks, administrators can generate immediate alerts and prevent service interruptions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
