Skip to content

Improve reporting of errors in bash scripts

At the moment, our CI and development setup scripts may fail without printing an unequivocal error message. Without knowing how the scripts work in detail, it may take some time to find exactly what caused the error.

I propose that we add something like the following to our scripts, to make it quicker to identify the source of any error by printing a clear message whenever it happens:

#!/bin/bash

set -e

error_handler() {
  exit_code=$?                
  line_no=$1                  
  print_header "ERROR"
  echo "Error in script '${BASH_SOURCE[1]}' at line ${line_no}."
  echo "Command: '${BASH_COMMAND}' failed with exit code ${exit_code}."
  exit ${exit_code}
}

trap 'error_handler ${LINENO}' ERR
Edited by Joao Afonso