0

I am using the following code to launch a command on another machine:

#!/bin/bash
/usr/bin/rsh -n $Host_Name "cat asdf.txt &"

And I am trying to obtain the PID of the cat command by using the following:

/usr/bin/rsh -n $Host_Name pid="$!"

But when I echo $pid, it is just blank. What am I doing incorrectly? Is there an easier way of obtaining the PID of the last command that was executed on a different machine?

Thanks

halexh
  • 3,021
  • 3
  • 19
  • 19
  • I think there are a few problems (but I could be wrong). Firstly, each invocation of rsh should probably spawn a new shell remotely, meaning that the $! variable won't be set in the new shell, and the variable of the previous shell would be lost. Secondly, by the syntax you're using, IIRC you're telling your local shell to set pid as the local $! before executing the rsh command. You should probably do something like `pid=$(/usr/bin/rsh -n $Host_Name 'echo $!')`, but remember that this will also return blank if it spawns a new remote shell instance. – Janito Vaqueiro Ferreira Filho Sep 28 '12 at 12:46

1 Answers1

2

You can only get the $! of the backgrounded command in the shell in which you started the command. If your command doesn't output anything to stderr, this could work:

/usr/bin/rsh -n $Host_Name "cat asdf.txt & echo $! >&2" 2> pidfile

The pid of the started command will then be stored locally in 'pidfile'.

Just a side-note: I would never use rsh. It is inherently insecure. I'd use ssh instead ;)

Friek
  • 1,533
  • 11
  • 13