Thursday, October 28, 2021

[SOLVED] Get PID of a remote process started with sshpass

Issue

I have a bash script which need to start some process on remote machine. I have done that using sshpass command.

I need to store the PID of that remote process.

I tried the following with a script:

sshpass -p password ssh user@ipaddr /bin/bash << EOF nohup process > /dev/null 2>&1 & echo $! > pid_file cat pid_file EOF

when I check with remote machine, the process is started and pid_file also has a number written in it. But the process id and number of pid_file do not match.

Executing the above set of commands directly on terminal without script, doesn't write anything in pid_file.

Can somebody help in storing the right pid of remote process.


Solution

sshpass -p password ssh user@ipaddr /bin/bash << EOF
nohup process > /dev/null 2>&1 & echo $! > pid_file
cat pid_file
EOF

The thing is that $! get's expanded not on the remote computer, but on your computer. When using the Here document, variable names are replaced by their values. So it gets expanded to whatever process you have had run in the background on you computer. You need to execute echo $! on the remote computer. That's why it's good to use -c and to always properly enclose the arguments.

sshpass -p password ssh user@ipaddr /bin/bash -c 'nohup process >/dev/null 2>&1 & echo $! > pid_file'

or you can just escape the $!:

sshpass -p password ssh user@ipaddr /bin/bash <<EOF
nohup process > /dev/null 2>&1 & echo \$! > pid_file
cat pid_file
EOF

or the best is to use quoted here string delimiter:

sshpass -p password ssh user@ipaddr /bin/bash <<'EOF'
nohup process > /dev/null 2>&1 & echo $! > pid_file
cat pid_file
EOF


Answered By - KamilCuk