Sujet : Re: (bash) Does the EXIT trap fire if/when bash is exited via a signal?
De : nn.throttle (at) *nospam* xoxy.net (Helmut Waitzmann)
Groupes : comp.unix.shellDate : 23. Aug 2024, 08:31:36
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <835xrrwy0n.fsf@helmutwaitzmann.news.arcor.de>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/27.1 (gnu/linux)
gazelle@shell.xmission.com (Kenny McCormack):
Note: This thread is entirely about bash. No other shells or "POSIX" are
relevant here. But comparisons between various versions of bash may be
relevant, since I think the behavior may have changed over the versions.
>
That said, suppose I have something like:
>
trap 'date > /tmp/somefile' EXIT
>
# Rest of script
>
Now, if during "Rest of script", say I hit ^C. Or ^\. Or, say I send a
signal via "kill" from another terminal. Does my exit trap get executed?
>
I've had varying results. I am pretty sure that at one point, the answer
was "no", but recently, I've noticed that when I exit via ^C, the EXIT trap
does execute. I'm curious what the "official" answer is.
>
The "official" answer should be in the "bash" documentation, but anyone who would like to investigate it, might let "bash" run the following script ("the_script")
#!/bin/sh
trap_command()
{
cat <<EOF
printf 'Executing %s trap at ' ${1:?} &&
date -- '+%F %T'
EOF
}
command="$( trap_command EXIT )" &&
trap "$command" EXIT &&
for signal
do
(
sleep -- 1 &&
printf 'Sending signal %s at ' "$signal" &&
date -- '+%F %T' &&
kill -s "$signal" -- "$$"
) &
sleep -- 3
done
providing signal names as parameters and observe what the shell will do, for example (
for signal in INT QUIT HUP TERM
do
bash ./the_script "$signal"
printf 'Script exited returning status %s\n' "$?"
done
)