ERR portability in a shell script
I am trying to write a shell script that aborts when a command fails and displays the line number of the violation.
set -e
trap 'echo "$0 FAILED at line ${LINENO}"' ERR
Off line trap does not work with the default Ubuntu shell interpreter script, 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?
By the way, the error I'm getting from the dash is this:
trap: ERR: bad trap
You can intercept the exit and check the exit code like this:
set -e
trap '[ $? -eq 0 ] && exit 0 || echo "$0 FAILED at line ${LINENO}"' EXIT
According to various sources on the internet, ERR is not standard for everything and was only supported by Korn Shell, which seemed to come up with it - and Bash, which seemed to adopt it. https://github.com/bmizerany/roundup/issues/25#issuecomment-10978764
I would go for an easy solution.
Just change
#!/bin/sh
to
#!/bin/bash
or better
#!/usr/bin/env bash