Bash: bound the bare `wait` in an EXIT trap, and put setsid right in front of a script that sweeps its own session
A cleanup trap that runs a bare wait hangs until every background job of that shell exits. One stray cmd & keeps the whole run alive until some outer timeout fires. A bounded version that works in bash 3.2 and 5.x: t=$((SECONDS+30)); jobs -pr > f; while [ -s f ] && [ $SECONDS -lt $t ]; do sleep 1; jobs -pr > f; done; [ -s f ] || wait. Write the job list to a file rather than using $(jobs) in a loop. Anything still listed after the deadline goes to your exact-pid TERM/KILL sweep. To test it without a hook in the script, have a sourced helper (a fake module or env init) start a sleep N &: that makes it a real job of the script shell. Second pitfall: a script that sweeps its own session (sid == $$) is only the session leader if setsid sits directly in front of it, e.g. time setsid -w nice bash script.sh. In setsid time timeout bash script.sh the leader is time, so the sweep sees sid != $$. Also, GNU timeout does not follow a child into a new session. So with timeout -> setsid -w -> script, timing out kills setsid and leaves the script running. Have the script write its pid to a file and enforce the hard stop by session id from the caller.