Skip to content

Instantly share code, notes, and snippets.

@vikaschenny
Created March 27, 2018 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikaschenny/d8f269e94afbc7c6ebb8ed85a5c5f69c to your computer and use it in GitHub Desktop.
Save vikaschenny/d8f269e94afbc7c6ebb8ed85a5c5f69c to your computer and use it in GitHub Desktop.
#!/bin/sh
usep=$( free -m | awk 'NR==2{printf "%.f\t\t", $3*100/$2 }')
if [ $usep -ge 20 ]; then
sync; echo 1 > /proc/sys/vm/drop_caches
fi
script -2
memory, cpu and disk space display script
#! /bin/bash
printf "Memory\t\tDisk\t\tCPU\n"
end=$((SECONDS+3600))
while [ $SECONDS -lt $end ]; do
MEMORY=$(free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }')
DISK=$(df -h | awk '$NF=="/"{printf "%s\t\t", $5}')
CPU=$(top -bn1 | grep load | awk '{printf "%.2f%%\t\t\n", $(NF-2)}')
echo "$MEMORY$DISK$CPU"
sleep 5
done
output
*********
Memory Disk CPU
9.34% 7% 0.00%
9.34% 7% 0.00%
9.34% 7% 0.00%
9.34% 7% 0.00%
commands
1.- Memory:
This will report the percentage of memory in use
free | grep Mem | awk '{print $3/$2 * 100.0}'
23.8171
free -m | awk 'NR==2{printf "%.2f%%\t\t", $3*100/$2 }'
9.24%
This will report the percentage of memory that's free
free | grep Mem | awk '{print $4/$2 * 100.0}'
76.5013
However, what we need from the above output is the total and used memory from the second line. A way to extract data from a given output is by using AWK.
AWK is an programming language used for text processing and data extraction. It is a standard feature of most UNIX systems. awk ‘NR==2’ extracts data form the second line. the $3 and $2 act as holders for the used and total values respectively.
2- Disk:
df -h | awk '$NF=="/"{printf "%s\t\t", $5}'
7%
wk ‘$NF outputs the number of fields. However, df -h | awk ‘$NF==”/” will go to that line which contains the character “/”. The $5 will select the field number five from that line. This ensures that the command extracts the correct percentage of disk used (which is %7 in our case).
3- CPU
top -bn1 | grep load | awk '{printf "%.2f%%\t\t\n", $(NF-2)}'
The top -bn1 command will execute the top command only once (n1 = one iteration) the “b” is used when we want to use “top” in a bash script or to output its data to a file.
“grep load” will output the line which contains the string “load”. $(NF-2) will count the number of fields on that line and decrement 2, thus outputs field #10, or the first 0.00 in the below output.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment