Here’s a bit of bash code that will exit if the previous command failed.

#!/bin/bash
ls /nonexistentdirectory
if [ $? -ne 0 ]; then
  echo "Previous command failed. Exiting."
  exit 1
fi