I would do something like this:
#!/bin/bash
trap : SIGTERM SIGINT
echo $$
find / >/dev/null 2>&1 &
FIND_PID=$!
wait $FIND_PID
if [[ $? -gt 128 ]]
then
kill $FIND_PID
fi
Some explanation is in order, I guess. Out the gate, we need to change some of the default signal handling. :
is a no-op command, since passing an empty string causes the shell to ignore the signal instead of doing something about it (the opposite of what we want to do).
Then, the find
command is run in the background (from the script's perspective) and we call the wait
builtin for it to finish. Since we gave a real command to trap
above, when a signal is handled, wait
will exit with a status greater than 128. If the process wait
ed for completes, wait
will return the exit status of that process.
Last, if the wait
returns that error status, we want to kill
the child process. Luckily we saved its PID. The advantage of this approach is that you can log some error message or otherwise identify that a signal caused the script to exit.
As others have mentioned, putting kill -- -$$
as your argument to trap
is another option if you don't care about leaving any information around post-exit.
For trap
to work the way you want, you do need to pair it up with wait
- the bash
man page says "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." wait
is the way around this hiccup.
You can extend it to more child processes if you want, as well. I didn't really exhaustively test this one out, but it seems to work here.
$ ./test-k.sh &
[1] 12810
12810
$ kill 12810
$ ps -ef | grep find
$