Skip to main

Shell script to convert PNGs into AVIF/WEBP using Squoosh CLI

  • squoosh
  • image optimisations
  • shell
  • avif
  • webp
1 min read
#!/bin/bash
if ! [ -x "$(command -v npx)" ]; then
	echo "npm isn't installed." >/dev/null >&2
	exit 1
fi

# TODO add other formats ex: webp
avif() {
	# customise parameters as needed
	local avif_options='{"quality": "30", "effort": "4"}'
	npx @squoosh/cli --avif "$avif_options" $1
}

format=$1
if [ -z "$format" ]; then
	echo "Format arg not specified. pass avif or webp as argument to the script." >/dev/null >&2
	exit 1
fi
if [[ "$format" != "avif" ]]; then
	echo "Invalid format specified" >&2
	exit 1
fi

for image in *.png; do
	base_name=${image%%.*}
	test_file="$base_name.avif"
	if [[ ! -f $test_file ]]; then
		avif $image
	else
		echo "$test_file already exists. Skipping..."
	fi
done

Usage

# Run this script file in the directory where you have png files
./squoosh.sh avif