0

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.

Nikita
  • 343
  • 1
  • 3
  • 17

1 Answers1

3
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
KamilCuk
  • 69,546
  • 5
  • 27
  • 60
  • 1
    Yes Bingo. Thanks Kamil. This escape character really helped. I cannot use `-c` option as there are some more verification required before executing the command. But one more issue is that `cat pid_file` is not getting saved in a variable. I did `var=$(cat pid_file)` but `echo $var` gives blank. What could be the reason of it? – Nikita Jun 14 '18 at 09:48
  • Everything you can do with here document or here string can be done with passing `-c` options to bash. Maybe try first saving the command string to a file, and then pass it to bash, like [here](https://stackoverflow.com/a/23464983/9072753). It's way cleaner that way. Also you can inspect the file for errors. – KamilCuk Jun 14 '18 at 10:35