Linux – Script to Check CPU Utilization

cpushell-script

I want a bash script that show the CPU consumption every minute and save it in a file.

The output would be like this:

11/09/2015 10:00: CPU: 60%
11/09/2015 10:01: CPU: 72%
11/09/2015 10:02: CPU: 32%

And so on… Can somebody help me ?

I can do it with # sar >> Result.txt but it shows the result every 15 minutes instead of every minute. Does anyone know how to fix this?

Best Answer

Put this into a bash script somewhere on your system (/opt for example):

#!/bin/bash

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

DATE=$(date "+%Y-%m-%d %H:%M:")

CPU_USAGE="$DATE CPU: $CPU_USAGE"

echo $CPU_USAGE >> /opt/cpu_usage.out

Then create a file called cpu_usage under /etc/cron.d/ with the following in:

*/1 * * * * root /opt/your_script.sh

This should execute the script once per minute, and output the CPU usage in a percentage format on a new line within the specified file.

Related Question