To kill a process, a
signal is sent to the process itself, some signals can be caught from the process, some other can't, typically SIGKILL (9) and SIGTERM (15) are used to terminate a process.
see
man 7 signal for furher info
You can instruct your 'script' to intercept some signal and execute some subroutine when receiving the signal, by using the the shell built-in command
trap: (
man 1 bash)
trap [-lp] [[arg] sigspec ...]
The command arg is to be read and executed when the shell receives signal(s) sigspec. If arg is absent (and there is
a single sigspec) or -, each specified signal is reset to its original disposition (the value it had upon entrance to
the shell). If arg is the null string the signal specified by each sigspec is ignored by the shell and by the com‐
mands it invokes. If arg is not present and -p has been supplied, then the trap commands associated with each sigspec
are displayed. If no arguments are supplied or if only -p is given, trap prints the list of commands associated with
each signal. The -l option causes the shell to print a list of signal names and their corresponding numbers. Each
sigspec is either a signal name defined in <signal.h>, or a signal number. Signal names are case insensitive and the
SIG prefix is optional.
what you may want is something like:
#!/bin/bash
# example trapping signals
#
function_terminate()
{
echo "this code will be executed upon receinving SIGUSR1 (signal 16)"
}
# script start here
#
trap function_terminate 16
#
# your script here
#
# echo "PID="$$
#
while true
do
sleep(1)
done
run the above script, you will find the following output while the script will remain in loop execution:
./signal
PID=8101
then, from a second terminal execute the following command:
kill -16 8101signal 16 is SIGUSR1, you will obtain the next output:
./signal
PID=8101
this code will be executed upon receiving SIGUSR1 (signal 16)
therefore you can put your commands to be executed upon receiving a signal (signal SIGUSR1), including an
exit command to terminate the script.
HTH

AS
EDIT: the
kill command took it's name because of it's original use, but should be more appropriate a name like
send_signal 