Search code examples
bashshellerror-handlingdash-shell

Portably trapping ERR in shell script


I'm trying to write a shell script that aborts when a command fails and displays the offending line number.

set -e
trap 'echo "$0 FAILED at line ${LINENO}"' ERR

Turned out the trap line does not work with Ubuntu's default shell script interpreter, dash. If I change the shebang line to #!/bin/bash this works but not with #!/bin/sh. Is there a way to make this work without relying on bash being present?

By the way, The error I get from dash is this:

trap: ERR: bad trap

Solution

  • You can trap on exit and test the exit code like this:

    set -e
    trap '[ $? -eq 0 ] && exit 0 || echo "$0 FAILED at line ${LINENO}"' EXIT