title: Bash: start remote python application through ssh and get its PID
body: <p>I'm creating a little bash script to copy new files from a windows machine to a remote linux centos server (i run this script using the git-shell) then i want to restart the python application thats running in the server to use those new files.</p>
  
  <p>The problem is that everytime i run this script i want to end the actual running process before i start it again, so i want to get the pid of the process i start and save it to a file in the remote host so i can read it from there the next time i run the program and kill it.</p>
  
  <p>My code by now looks similar to this:</p>
  
  <pre><code>echo "Copying code files to server..."
  # The destination folder has to exist in the server
  scp -r ./python/ root@myserver:/root/
  
  echo "Checking for running processes..."
  
  if ssh root@myserver 'ls dmr.pid &gt;/dev/null'; then
      echo "PID file exists, reading file..."
      PID=$(ssh root@myserver 'cat dmr.pid')
  
      # Terminate the actual process
      echo "Terminating the process with PID '$PID'..."
      ssh root@myserver 'kill $PID'
  else
      echo "PID file doesn't exist, not known processes running"
  fi
  
  # Restart the server and get the PID
  echo "Restarting the server..."
  ssh root@myserver 'python /root/python/run_dev_server.py &gt; /dev/null 2&gt;&amp;1 &amp;'
  
  SERV_PID=$(ssh root@myserver 'echo $!')
  
  echo "Saving PID to file dmr.pid"
  ssh root@myserver "echo '$SERV_PID' &gt; \"dmr.pid\""
  
  echo "Sucesfully finished!"
  </code></pre>
  
  <p>The important lines are:</p>
  
  <pre><code>ssh root@myserver 'python /root/python/run_dev_server.py &gt; /dev/null 2&gt;&amp;1 &amp;'
  SERV_PID=$(ssh root@myserver 'echo $!')
  </code></pre>
  
  <p>the problem with this is that the script finishes but the file ends up empty as well as the $SERV_PID variable.</p>
  
  <p>And if i dont redirect the outputs and just do something like this:</p>
  
  <pre><code>SERV_PID=$(ssh root@myserver 'python /root/python/run_dev_server.py &amp; echo $!')
  </code></pre>
  
  <p>i get stuck after "Restarting the server" and never get the PID or the file that will contain it or even the end of the script.</p>
  
  <p>But if i run this right in the console:</p>
  
  <pre><code>ssh root@myserver 'python /root/python/run_dev_server.py &amp; echo $!'
  </code></pre>
  
  <p>i get a PID printed to the terminal.</p>
  
  <p>Any advice on this would be really appreciated.</p>