Bash – Show error message if bash script terminates due to set -e

basherror handling

I want to terminate script if any command returns nonzero value, what I achieved by adding set -e.

Now script fails on encountering problems (what is desirable) but it is easy to miss it – some commands may return error code without printing what failed.

What is the standard way for adding error message warning that script was terminated?

Best Answer

With help of Bash capture any error like -e but don't exit, do something else I found way to show error message before terminating script.

One may use trap to ensure that specified code is executed on encountering error, what happens immediately before -e option terminates script. For example

set -e

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

trap 'err_report $LINENO' ERR

echox
echo "x"

will result in

test.sh: line 9: echox: command not found
Error on line 9
Related Question