The first thing I notice is a missing
set -eu
set -o pipefail
at the top of the script, which is equivalent to ON ERROR RESUME NEXT
in BASIC.