Bash Error Handling – Using Trap, ERR, and Echoing the Error Line

basherror handlingshell-scripttrap:

I'm trying to create some error reporting using a Trap to call a function on all errors:

Trap "_func" ERR

Is it possible to get what line the ERR signal was sent from? The shell is bash.

If I do that, I can read and report what command was used and log/perform some actions.

Or maybe I'm going at this all wrong?

I tested with the following:

#!/bin/bash
trap "ECHO $LINENO" ERR

echo hello | grep "asdf"

And $LINENO is returning 2. Not working.

Best Answer

As pointed out in comments, your quoting is wrong. You need single quotes to prevent $LINENO from being expanded when the trap line is first parsed.

This works:

#! /bin/bash

err_report() {
    echo "Error on line $1"
}

trap 'err_report $LINENO' ERR

echo hello | grep foo  # This is line number 9

Running it:

 $ ./test.sh
 Error on line 9
Related Question