Error handler
trap 'echo "ERROR on line $LINENO"; exit 1' ERR
This line is an error handler (or an exception catcher). It tells Bash: “The very moment any command fails, run this specific piece of code before you shut down.”
Anatomy of the Command
- trap ’…’: This tells Bash to listen for a specific event or signal. When that event happens, execute the code inside the single quotes.
- ERR: This is the specific event Bash is listening for. It triggers whenever a command returns a non-zero exit code (a failure).
- $LINENO: This is a magical built-in Bash variable that always contains the exact line number of the script currently being executed.
- exit 1: This forces the script to stop immediately and return a failure status (1) to the system.
#!/bin/bash
set -euo pipefail
trap 'echo "ERROR on line $LINENO"; exit 1' ERR
cd /non_existent_folder
echo "Moving on..."