通过ssh在后台运行脚本时,我无法在远程计算机上的文件中存储任何PID
。
我需要将脚本过程的PID
存储在一个文件中,以便在需要时将其杀死。在远程计算机上运行确切命令时,它正在运行,为什么通过ssh无法运行?
以下命令出了什么问题?
ssh user@remote_machine "nohup ./script.sh > /dev/null 2>&1 & echo $! > ./pid.log"
结果:文件pid.log
已创建但为空。
预期:文件pid.log
应该包含正在运行的脚本的PID
。
答案 0 :(得分:1)
使用
ssh user@remote_machine 'nohup ./script.sh > /dev/null 2>&1 & echo $! > ./pid.log'
OR
ssh user@remote_machine "nohup ./script.sh > /dev/null 2>&1 & echo \$! > ./pid.log"
问题:
Your $!
was getting expanded locally, before calling ssh at all.
更糟糕的是,在调用ssh命令之前,如果在后台盯着某个进程,则$!
将扩展为该进程,并且完整的ssh命令将扩展为包含该PID作为echo参数。 / p>
例如
$ ls &
[12342] <~~~~ This is the PID of ls
$ <~~~~ Prompt returns immediately because ls was stared in background.
myfile1 myfile2 <~~~~ Output of ls.
[1]+ Done ls
#### At this point, $! contains 12342
$ ssh user@remote "command & echo $! > pidfile"
# before even calling ssh, shell internally expands it to:
$ ssh user@remote "command & echo 12342 > pidfile"
这会将错误的PID放在pidfile中。