#!/bin/sh
term_handler () {
if [ "$ok_to_exit" -eq 1 ]; then
echo 'exiting'
exit
else
echo 'refusing to exit'
fi
}
trap term_handler TERM
ok_to_exit=0
pkill -f test.sh
ok_to_exit=1
while true; do
echo 'working...'
sleep 2
done
This script installs a signal handler, the `term_handler` function, which will exit the script upon receiving a `TERM` signal _if_ the `ok_to_exit` variable's value is `1`.
In the body of the script is a loop simulating some form of work being carried out. The important bit is that before calling `pkill` (you mach change this to your `killall` command), it sets `ok_to_exit` to `0`, and directly afterwards it sets it to `1`.
When sending out the `TERM` signal to all matching processes, it will receive the signal itself, but it will refuse to exit. Any other matching processes, _if it's not also in the exact same state_ (which could happen if you started the script more than once simultaneously), would terminate.