One way to do this is through signals and traps. Here is a simple example:
#!/bin/bash me=$$
Comments are self-sufficient (hopefully). The first part starts the background process, which simply sleeps for a certain period of time (10 seconds in this example), and then, when it wakes up, sends SIGUSR1 to the original process.
The shell call catches this (using trap ) and simply issues kill to its own PID, stopping the process.
The rest is just an endless loop - it's a trap that kills the script and terminates the loop.
Technically, you donβt need a trap in the above example: the background process can simply issue kill $me directly, but I turned it on for completeness, since you can use it as a hook to perform other actions (for example, if you do not want to die, but set the flag and complete the loop naturally, or do you have some sort of cleanup to complete).
source share