Shell script: CPU, memory and disk usage
Shell script that prints memory, root disk and CPU load usage on a Linux system.
This shell script (POSIX sh compatible) prints the memory usage, the root disk usage and the CPU load on one line each.
#!/bin/sh
free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }'
df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'
top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}'
How it works
free -mdisplays memory in MB; line 2 (Mem:) holds the total and the used memory.df -hkeeps only the line for the/mount point, with its size, used space and usage percentage.top -bn1runs a single iteration in batch mode; theload averageline holds the load averages, and$(NF-2)is the 1-minute average.
Notes
- The
%dformat keeps only the integer part of thedf -hvalues: 1.5G is displayed as 1GB. - The
GBlabel assumes that sizes are in gigabytes.df -hcan also show values in MB or TB.