Script to calculate Average CPU Load from SAR

Just a simple script here to calculate average CPU load from SAR data:

#!/bin/bash

# Get the list of available SAR files
sar_files=$(ls /var/log/sa/sa[0-9][0-9])

# Initialize variables for total and count
total=0
count=0

# Iterate over each SAR file
for file in $sar_files; do
    # Extract the relevant fields from the sar file
    queue_sizes=$(sar -q -f "$file" | awk '/Average:/ {print $5}')

    # Calculate the sum of queue sizes
    for size in $queue_sizes; do
        total=$(echo "$total + $size" | bc)
        count=$((count + 1))
    done
done

# Calculate the average queue size if count is non-zero
if [ $count -gt 0 ]; then
    average=$(echo "scale=2; $total / $count" | bc)
    echo "Average CPU usage based on SAR queue size: $average"
else
    echo "No SAR data available or count is zero."
fi

Execute it and you’ll see an output like this: