3 ms·
There's a bit more nuance in my opinion. If your cleanup logic is no more complicated than "perform some cleanup whenever the script exits for any reason, with
by pcthrowaway 3y ago
There's a bit more nuance in my opinion.
If your cleanup logic is no more complicated than "perform some cleanup whenever the script exits for any reason, without concern for what state the things to clean up are in", I think trapping everything and calling the cleanup function is fine.
If you have to do anything more complicated, it's probably a better idea to stick all that logic into a non-bash program. You can do it in Bash if you know what you're doing, but it's going to be ugly, hacky, error-prone, and tedious.
Not using traps, it's clearer what happens at specific points in the execution of the rest of the code, so simpler to reason about how to deal with those cases as/where they happen.
You can stick all kinds of logic into the cleanup function, but again, it's ugly.
The second is different events can trigger an exit trap, and those may have different implications on what's going on.
The third is there's parts of standards left out about what happens during/after a trap or when they get called, what data you have available, and different implementations can behave differently.
Which is why I think it's preferable not to do this in bash if you have any concern for why the program is exiting
Fourth is that sometimes people will use an exit trap to, say, report on a failure, but they may have lost context of what block they were in when it exited, and now the error reporting doesn't tell you everything you wanted to know.
If you need any tracing, the only way this makes sense in bash is when running with -evx (errexit, verbose, trace) so you know exactly where you exited. This isn't always a bad idea, though -vx probably is most of the time.
If you think you can do any complex logic in the trap function then you have to consider whether that logic might fail at any point, and depending on the signal there's a good chance you're on a clock as well.