Reputation: 1503
I'm trying to remove some bashisms from a shell script.
I can't figure out how I would replicate 'trap ERR': ERR is not a signal, and is not in the standard, but is a common bashism (see e.g. the LDP guide).
How do I replicate trap ERR
in a standards-compliant /bin/sh
script?
Upvotes: 6
Views: 1893
Reputation: 531325
You can use a combination of set -e
and trap ... EXIT
.
#!/bin/sh
set -e
err_handler () {
[ $? -eq 0 ] && exit
# Code for non-zero exit status here
}
trap err_handler EXIT
set -e
will cause the script to exit whenever an unguarded command has an non-zero exit status. The error handler will be called unconditionally when the script exits, but inside the handler you can simply exit if the current exit status is 0, i.e., we reached it without any errors occurring.
By "unguarded" command I mean a command that isn't run in a context where a non-zero exit status is reasonably expected to occur, such as in the condition for an if
statement.
Upvotes: 11
Reputation: 3154
ERR is not really a signal. See: http://en.wikibooks.org/wiki/Bourne_Shell_Scripting/Debugging_and_signal_handling#Err..._ERR.3F at the bottom.
Upvotes: 1