Re: A defer command as a bash loadable builtin

Koichi Murase <[email protected]> Fri, 26 Jun 2026 09:24:42 +0900
Newsgroups gmane.comp.shells.bash.bugs
Message-ID <CAFLRLk9SCPRZ9+PnghidtjugM-Z7E8zh+utvvGNoAk8BeOzMHA@mail.gmail.com>
2026=E5=B9=B46=E6=9C=8825=E6=97=A5(=E6=9C=A8) 21:24 L=C3=A9a Gris <lea.gris=
@noiraude.net>:
> $ defer -p INT
> trap -- 'echo "hello world"' SIGINT
> $ defer 'rm -f -- "$tmp"; printf "Cleanup done on %s\\n" "$tmp"' INT
> $ defer -p INT
> trap -- 'rm -f -- "$tmp"; printf "Cleanup done on %s\\n" "$tmp"
> echo "hello world"' SIGINT

I didn't carefully check `defer.c', but if the above is what is
achieved by the suggested loadable builtin, the builtin seems a very
thin wrapper of the trap builtin. The implementations by shell
functions posted by others are functionally equivalent and much
simpler than the C implementation with 195 lines.

The fork cost of subshells and the issue with the printf usage aren't
fundamental issues in implementing them with a shell function. As long
as a shell function is properly implemented, those issues shouldn't
arise. One can use no-fork command substitutions, as mentioned by
Oguz, and one can use =C2=ABprintf '%s\n%s' ...=C2=BB or simply =C2=AB"$1<n=
ewline>${
trap -P "$2"; }"=C2=BB, as suggested by Andreas and Gregory.

--
Koichi