Thursday, 9 April 2020

Bash script to monitor cpu usage in Linux

Script to monitor cpu usage 

$ vi cpu_usage.sh

#!/bin/bash

CPU_USAGE=$(top -b -n2 -p 1 | fgrep "Cpu(s)" | tail -l | awk -F'id,' -v prefix="$prefix" '{ split($1, vs, ","); v=vs[length(vs)]; sub("%", "", v); printf "%s%.1f%%\n", prefix, 100 -v}' )

DATE=$(date "+%d %B %Y %H:%M")
CPU_USAGE="$DATE CPU: $CPU_USAGE"
echo $CPU_USAGE >> /var/log/scripts/cpu_usage.log

$ ./cpu_usage.sh

$ cat /var/log/scripts/cpu_usage.log
09 April 2020 08:36 CPU: 3.2% 0.2%
09 April 2020 15:00 CPU: 9.7% 0.0%
09 April 2020 15:34 CPU: 0.0% 0.2%

No comments:

Post a comment