Getting the pid of a job running in the background remotely

I am trying to run a task in the background on a remote computer and get its PID code so that it can be killed later. So far I have come to 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 this will not work. I get

bash: syntax error near unexpected token `;'

but I don’t know what the correct syntax will be.

+5
source share
3 answers

You have a mistake because you are ';' is redundant, try 'vmstat 1 1000> vmstat.log and echo $!'

But I'm not sure that it will work, because after logging out the process will get SIGHUP. Take a look at nohup (1).

+3
source

Try to surround the background command in braces:

PID=`$REMOTE_EXEC '{ vmstat 1 1000 > vmstat.log & }; echo $!'`
+2

, $! :

$REMOTE_EXEC "{ vmstat 1 1000 > vmstat.log & }; echo \$!"

P=`$REMOTE_EXEC "{ vmstat 1 1000 > vmstat.log & }; echo \\\$!"`
0

All Articles