How can I trap errors and interrupts in GNU make?

Cyrus picture Cyrus · Jun 10, 2009 · Viewed 8.8k times · Source

I'm wondering if there's a way to implement trap in GNU make, similar to that built into BASH?

If the user presses CTRL-C, or if make itself fails (non-zero exit), I'd like to call a particular target or macro.

Answer

Kevin picture Kevin · Sep 25, 2015

At this point in time, GNU make doesn't have native support.

There is a reliable workaround however:

.PHONY: internal-target external-target

external-target:
  bash -c "trap 'trap - SIGINT SIGTERM ERR; <DO CLEANUP HERE>; exit 1' SIGINT SIGTERM ERR; $(MAKE) internal-target"

internal-target:
  echo "doing stuff here"

This catches interruptions, terminations AND any non-zero exit codes.

Note the $(MAKE) so cmdline overrides and make options get passed to submake.

On trap:

  • clear trap handler (with -)
  • do the cleanup
  • exit with non-zero exit status, so build automation tools report the failed build.

DELETE_ON_ERROR does NOT work for directories, so this is key for cleaning up after mktemp -d, for example

Replace <DO CLEANUP HERE> with valid CMD.