GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)

[curious ~]# cat ./trap-term
trap 'echo TRAP' TERM
sleep 30
[curious ~]# ./trap-term & sleep 3; kill -TERM %1
[1] 3141
   <... pause - 3s>
[curious ~]# Terminated
[1]+  Exit 143                ./trap-term

Reaction is immediate (3s)?!

[curious ~]# cat ./tt
./trap-term & sleep 3; kill -TERM %1
[curious ~]# ./tt <... pause - 3s>
[curious ~]# <... pause - 30s> TRAP

Reaction agrees with bash doc:

If Bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes.

The question is why the first variant is so much faster than other??


Test in another distro:

Ubuntu 20.04.3 LTS (GNU/Linux 4.4.0-19041-Microsoft x86_64); GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu): the same first result with "Terminated" and "TRAP" after 3s

@zevzek "there are no jobs in shell scripts"??!

curious ~$ cat ./ttj 
./trap-term & sleep 3; jobs; kill -TERM %1 
curious ~$ ./ttj 
[1]+  Running                 ./trap-term & 
curious ~$ TRAP
  • Are you sure the job is always %1? It's safer to use $!.
    – choroba
    Nov 10, 2021 at 9:35
  • I can't really reproduce your first example. The TRAP output always comes after 30 seconds, not 3. What shell are you using? The bash shell does not usually output "Exit 143". Mine says "Done" there instead. I also can't reproduce your second example. The script always exits after 3 seconds and the TRAP output comes after 30. You will have to say more about the context of your issue.
    – Kusalananda
    Nov 10, 2021 at 10:23
  • GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu); " TRAP output comes after 30" - like I say
    – curious
    Nov 10, 2021 at 10:28
  • @curious It's unclear what the timing are in your example. In the first example, you say "pause 3s", then you show a prompt (with the text Terminated, which I never see when I test), then TRAP. So it's clear when the prompt shows up, but not when TRAP is outputted after that. In the second example, you say "pause 30s" before the prompt with the text TRAP. So it appears that the prompt and the text appears at the same time. Also, "immediate" is not the same as "after 3 seconds", which fuels the confusion.
    – Kusalananda
    Nov 10, 2021 at 10:35
  • first: TRAP output comes after 3; second: TRAP output comes after 30
    – curious
    Nov 10, 2021 at 10:36

1 Answer 1


Ok, I've found the answer by myself.

Second case: noninteractive shell - job control is disabled - needs set -m.

[curious ~]# cat ./tta
set -m; ./trap-term & sleep 3; kill -TERM %1
[curious ~]# ./tta 
<... pause - 3s>
[curious ~]#

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .