Bash Script: Calculate before/after averages

I’ve been doing some performance testing, and wanted a quick way to test how well or poorly changes affect a site. Normally I’d whip out the ol’ calculator app and do this manually. That got tiring after a while, so instead with the help of ChatGPT, I made this little bash script that will do the work for you:


# Function to calculate the average of a list of numbers
average() {
	local sum=0
	local count=0

	for num in "$@"; do
		sum=$(echo "$sum + $num" | bc -l)

	echo "$sum / $count" | bc -l

# Parse arguments
for i in "$@"; do
	case $i in
		# unknown option

# Check if both BEFORE and AFTER parameters are provided
if [ -z "$BEFORE" ] || [ -z "$AFTER" ]; then
	echo "Error: Missing required parameters."
	echo "Usage: $0 --before=<comma-separated-values> --after=<comma-separated-values>"
	exit 1

IFS=',' read -ra BEFORE_LIST <<< "$BEFORE"
IFS=',' read -ra AFTER_LIST <<< "$AFTER"

# Calculate average for before and after lists
BEFORE_AVG=$(printf "%.2f\n" $(average "${BEFORE_LIST[@]}"))
AFTER_AVG=$(printf "%.2f\n" $(average "${AFTER_LIST[@]}"))

echo "Before average: $BEFORE_AVG"
echo "After average: $AFTER_AVG"

# Calculate average percent increase, decrease or no change for the list
if [ "$BEFORE_AVG" != "0.00" ]; then
	PERCENT_CHANGE=$(echo "(($AFTER_AVG - $BEFORE_AVG) / $BEFORE_AVG) * 100" | bc -l)
	if [ "$(echo "$PERCENT_CHANGE > 0" | bc -l)" -eq 1 ]; then
		printf "Average percent increased: %.2f%%\n" "$PERCENT_CHANGE"
	elif [ "$(echo "$PERCENT_CHANGE < 0" | bc -l)" -eq 1 ]; then
		printf "Average percent decreased: %.2f%%\n" "$PERCENT_CHANGE" | tr -d '-'
		echo "No change in average."
	echo "Percent change from before to after: undefined (division by zero)"
Code language: Bash (bash)

It runs like this:

$ --before=13.07,9.75,16.14,7.71,10.32 --after=1.22,1.28,1.13,1.19,1.26
Before average: 11.40
After average: 1.22
Average percent decreased: 89.30%

In this instance, it was calculating seconds–but you need to remember that it only goes to two decimal places, so if you need something finer you’ll need to adjust the code or your inputs.

Happy Slacking!

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.


One response to “Bash Script: Calculate before/after averages”

  1. […] an update, or an evolution of my earlier script that did some simple math for me, I’ve made one that will full-on test a URL while I’m making changes to see what the […]

Leave a Reply