Le 26/06/2026 à 12:32, Koichi Murase écrivait :
2026年6月26日(金) 16:42 Léa Gris <[email protected]>:

For the design, I'm not sure if it is robust to concatenating the trap
strings by a newline.  When one of the registered trap strings
contains a syntax error, it would affect the subsequent commands.
When one of the trap strings contains the builtin changing the control
flow, such as `return', `break', and `continue`, subsequent registered
trap strings would be skipped. I think the proper implementation
should manage an array for each signal, which is separate from the
store managed by the trap builtin.

Introducing a distinct trap store might come with its own side effects essentially because it would violate the Single Responsibility Principle.

For the scope of this project, I prefer to stick with defining the interface. Defer is a concept and keyword that exists in other languages such as Go, it fits a real need to provide a common known tooling for LIFO chained traps.

My implementation is thin atop trap because I reckon that in the current shell script paradigm, trap is the authority holder for trap handling.

As a demonstrator of this interface for the Bash shell environment, defer is a standard contract for stacking LIFO handlers on a signal.


It is somewhat subjective, but another point is that I have difficulty
in associating the suggested behavior with "deferring trap commands".
The hooks into some of the (pseudo-)signals, such as EXIT and RETURN,
may be considered as some kind of "deferring" of cleanup, etc., but,
in general, we can't say (pseudo-)signals are used for deferring
commands.

You express very valid concerns with EXIT and especially RETURN. I did not ignore them, I perfectly understand where you are coming from and I investigated those as well.

The RETURN trap is not a SIG trap, it is a special feature of Bash, and for now this feature does not distinguish a frame of execution. If an inner function call defines a RETURN trap, it might erase the outer defined trap. And with command prepend concatenation, the inner function prepending its handler will cause the outer RETURN to also execute it.

Those are issues directly related to how the current trap implementation is designed. It would be a good exercise and project to investigate how to improve the trap command itself without breaking POSIX compatibility or causing side effects in existing scripts. But I'd put that aside the defer builtin I propose here.

Let's keep defer as a wrapper to trap for now, and let's see if we can make trap smarter without breaking backward compatibility and POSIX shell conformance as a different project.


--
Léa Gris

Reply via email to