Hamy
Hamy

Reputation: 21562

Bash ERR trap halting program

This trap on ERR halts the script. Other examples show that a trap can be used to continue program execution, so why does this halt?

#!/bin/sh -e
trap 'echo error' ERR
echo begin
false
echo end

Returns

$ ./test.sh
begin
$ 

Upvotes: 1

Views: 788

Answers (1)

Hamy
Hamy

Reputation: 21562

ERR traps are still affected by the shell's errexit option (set -e). The problem here is that the shebang sets errexit. This will work as expected:

#!/bin/sh
trap 'echo error' ERR
echo begin
false
echo end

returning

$ ./test.sh
begin
error
end
$ 

errexit is very aggressive. It will instantly kill the script if any statement is non-true.

This will push you as a developer to write very defensively. For example, you cannot ever use $? with errexit because the script itself will not continue if the exit code is non-zero. This "push the developer to get it perfect" approach is useful for some scenarios, e.g. commonly errexit is used to run very early boot scripts when automatically provisioning a system.

If you find yourself in an errexit scenario but needing to handle expected errors, here is the common approach:

#!/bin/sh -e 
trap 'echo error' ERR
echo begin
false || { echo "It was false"; } 
echo end

Which will output:

begin
It was false
end

Note that the trap is still not fired, because no error happened. As far as I can tell, the "error" condition referred to by ERRtrap and errexit is functionally identical

Upvotes: 2

Related Questions