I want to start a couple of jobs on different machines using ssh. If the user then interrupts the main script I want to shut down all the jobs gracefully.

Here is a short example of what I'm trying to do:

#!/bin/bash
trap "aborted" SIGINT SIGTERM
aborted() {
    kill -SIGTERM $bash2_pid
    exit
}

ssh -t remote_machine /foo/bar.sh &
bash2_pid=$!
wait

However the bar.sh process is still running the remote machine. If I do the same commands in a terminal window it shuts down the process on the remote host.

Is there an easy way to make this happen when I run the bash script? Or do I need to make it log on to the remote machine, find the right process and kill it that way?

edit: Seems like I have to go with option B, killing the remotescript through another ssh connection

So no I want to know how do I get the remotepid? I've tried a something along the lines of :

remote_pid=$(ssh remote_machine '{ /foo/bar.sh & } ; echo $!')

This doesn't work since it blocks.

How do I wait for a variable to print and then "release" a subprocess?

Edit
Report