tags:

views:

556

answers:

2

I am trying to launch in the background a job on a remote machine and get its PID so that I can kill it later on. What I have come up with so far is the following:

#!/bin/bash

IP=xxx.xxx.xxx.xx
REMOTE_EXEC="ssh $IP -l root"

# The following does NOT work, I am trying to get the PID of the remote job
PID=`$REMOTE_EXEC 'vmstat 1 1000 > vmstat.log & ; echo $!'`

# Launch apache benchmark
ab -n 10 http://$IP/

$REMOTE_EXEC "kill $PID"

Unfortunately it does not work. I am getting a

bash: syntax error near unexpected token `;'

but I don't know what the right syntax would be.

+2  A: 

You got the error, because you ';' is redundant, try 'vmstat 1 1000 > vmstat.log & echo $!'

But I am not sure it gonna work, because after you logout, the process will receive SIGHUP. Look at nohup(1).

dmitri
It does work, even without using nohup. Thanks!
davitenio
Yeah, you are right...May be, it happens, because in this case ssh does not "login" you (from ssh(1): "If command is specified, it is executed on the remote host instead of a login shell.").
dmitri
+1  A: 

Try surrounding the backgrounded command in curly braces:

PID=`$REMOTE_EXEC '{ vmstat 1 1000 > vmstat.log & }; echo $!'`
Mike from America