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
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
According to various sources on the internets, ERR is not standard at all and only supported by the Korn Shell - which seemed to invent it - and Bash, which seemed to adopt it. https://github.com/bmizerany/roundup/issues/25#issuecomment-10978764
I would go for the easy solution.
Simply change
#!/bin/sh
to
#!/bin/bash
or better
#!/usr/bin/env bash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With