0

我有一个 bash 脚本,它需要在远程机器上启动一些进程。我已经使用sshpass命令完成了。

我需要存储该远程进程的 PID。

我用脚本尝试了以下操作:

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

当我检查远程机器时,该进程已启动,并且 pid_file 中也写入了一个数字。但是进程id和pid_file的数量不匹配。

在没有脚本的情况下直接在终端上执行上述命令集,不会在 pid_file 中写入任何内容。

有人可以帮助存储远程进程的正确 pid。

4

1 回答 1

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

问题是$!get 不是在远程计算机上扩展的,而是在您的计算机上扩展的。使用Here 文档时,变量名将替换为它们的值。因此,它会扩展到您在计算机后台运行的任何进程。您需要echo $!在远程计算机上执行。这就是为什么最好使用-c并始终正确包含参数的原因。

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

或者你可以逃避$!

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

或者最好是使用这里引用的字符串分隔符:

sshpass -p password ssh user@ipaddr /bin/bash <<'EOF'
nohup process > /dev/null 2>&1 & echo $! > pid_file
cat pid_file
EOF
于 2018-06-14T09:32:46.190 回答