On Sat, 28 Sep 2024, Greg Wooledge wrote:

On Sat, Sep 28, 2024 at 14:53:10 +0100, Tim Woodall wrote:
Is there a way in bash to guarantee that a trap gets called for cleanup
in a script?

#!/bin/bash
trap cleanup EXIT
cleanup() {
   ...
}

This works in bash -- i.e., it calls the cleanup function regardless
of whether the shell exits by calling "exit", or by falling off the
end of the script, or by receiving a fatal signal.  It does NOT work in
/bin/sh (dash, or any other implementation).  You have been warned.


That's exactly what I'm doing but somehow it's not working. (See below
for what the problem seems to be)

But I also cannot create a small testcase to reproduce.

It's a pain, I'm trying to debug something that takes a very long time
to run and the cleanup requires a complex ordering of unmounting,
deleting loop devices and deleting files  which all happens
automatically normally.

But as soon as I send the (copious) output to a pipe, then it doesn't
cleanup and I'm left having to do it by hand.

I guess I'll have to try and debug what isn't working.

Hmmm, I've managed to fix it. The problem seems to be related to using
echo in the exit trap itself while both stderr and stdout are redirected
- e.g. via |& tee log

If I change the echo in the trap function to /bin/echo then it works! (I
don't see the output anywhere but that isn't really a problem in this
case - I know why it's aborted!)

I still can't create a small testcase but maybe this gives someone a
clue what issue I'm hitting?

In this particular case it's almost certain that the tee program will
have gone away before the bash script calls the exit handler.

apt-cache policy bash
bash:
  Installed: 5.2.15-2+b7

Reply via email to