Here is a simplified version of Antony's answer, targeting POSIX sh:
remove_blank_pages() {
pdf="$1"
# Execute the PDF using Ghostscript, outputting to the ink coverage device.
# For each page, the ink coverage device prints the ratio of coverage for C, M, Y, and K.
ink_coverage=$(gs -q -o - -sDEVICE=inkcov "$pdf")
num_pages=$(printf '%s\n' "$ink_coverage" | wc -l)
# If any of the four channels have a nonzero average, consider this page nonblank.
non_blank_pages=$(printf '%s\n' "$ink_coverage" |
awk '$1 + $2 + $3 + $4 > 0 {printf("%d ", NR) }')
num_non_blank_pages=$(echo "$non_blank_pages" | wc -w)
if [ "$num_pages" -ne "$num_non_blank_pages" ]; then
# We will not be quoting the page parameter.
# We do this not to permit globbing (hence disabling it),
# but to allow splitting by IFS (hence leaving that alone).
set -f
# shellcheck disable=SC2086
pdftk "$pdf" cat $non_blank_pages output temp.pdf verbose
set +f
mv temp.pdf "$pdf"
fi
}
You could surely tweak the threshold in the awk statement; for my usecase, looking for fully-blank pages sufficed.
If you want to run pdftk unconditionally, you could simplify the code even further, since the page count would not need to be recorded.