Cancel background script run from any shell

I have a script I usually keep running in the background; it sets up port forwarding I use for database connections while developing an app whose details are irrelevant at the moment. Because I always want this running, I have it set to start up whenever a new shell opens - it checks if that port is in use and starts forwarding if not.

function forward {                                                                   
    if lsof -Pi :55433 -sTCP:LISTEN -t >/dev/null ; then
        echo "redirect already running"
    else
        target=$(~/environment-destination.sh staging)
        ~/forwarder.sh 55433 stuff.rds.amazonaws.com:5432 $target > /dev/null &
        echo "redirect running"                                                   
    fi                                                                           
}

What I want to do is to make it possible for another script, run in any shell, to stop this script and free up the port. (Primarily I want this because I occasionally want to set up forwarding to the production instance instead of the staging environment.) I tried saving the pid to a file and running pkill on it, but this doesn't work - and pgrep doesn't find it either. Is there a better approach?


Solution 1:

You Should create a shell script like this :

function forward {                                                                   
    if lsof -Pi :55433 -sTCP:LISTEN -t >/dev/null ; then
        echo "redirect already running"
    else
        target=$(~/environment-destination.sh staging)
        ~/forwarder.sh 55433 stuff.rds.amazonaws.com:5432 $target > /dev/null &
        echo $! > /tmp/forward.pid
        echo "redirect running"                                                   
    fi                                                                           
}

Then killing your forwarding is done by kill $(cat /tmp/forward.pid)