Bash script should only kill those instances of another script’s that it has launched

bashprocess

In the current situation, a certain script 'calling.sh' launches another script 'called.sh' in the background, performs other operations, sleeps for a while, and then terminates 'called.sh' with a pkill called.sh. This works fine.

Then, I would also like to launch 'called.sh' from other terminals as a standalone script at any other time, whether before or after launching calling.sh. These independent instances should not be killed by 'calling.sh'.

How can I achieve this? Intuition says that the calling script should be able to tell the process it started from any other namesakes that are running in the meantime.

As a variant, 'calling.sh' may also launch 'called' which is a symbolic link to 'called.sh'. Does this complicate managing the above situation? Which specific cautions and adjustments does using a symbolic link require?

Best Answer

Don't use the name to kill it. Since the calling.sh script is calling the process you later want to kill, just use $! (from man bash):

! Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin

So, if you're calling.sh is like this:

called.sh &
## do stuff
pkill called.sh

Change it to this:

called.sh &
calledPid=$!
# do stuff
kill "$calledPid"
Related Question