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

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!

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.

%d bloggers like this: