在进程终止时运行脚本

时间:2016-03-02 20:40:34

标签: bash shell amazon-web-services

我在AWS EC2类型的环境中进行计算。我有一个在headnode上运行的脚本,然后在VM上执行shell命令,它从headnode父shell分离。

headnode.sh

#!/bin/bash
...
nohup ssh -i vm-key ubuntu@vm-ip './vm_script.sh' &
exit 0

我这样做的原因是vm_script需要很长时间才能完成。所以我想将它从headnode shell中分离出来,让它在VM的后台运行。

vm_script.sh

#!/bin/bash
...
ssh -i head-node-key user@head-node-ip './delete-vm.sh'
exit 0

VM完成任务后,会向headnode发送命令以删除VM。

在VM上完成脚本后,是否有更可靠的方法在headnode上执行最终脚本?

例如,在我启动vm_script.sh后,我是否可以在headnode上启动另一个脚本,等待VM上的PID完成?

1 个答案:

答案 0 :(得分:0)

假设您信任网络链接,更通用的可靠方式是更简单的方法。我会重写headnode.sh,如下所示:

#!/bin/bash
...
ssh -i vm-key ubuntu@vm-ip './vm_script.sh' && ./delete-vm.sh 

上面的脚本等待vm_script.sh终止,如果./delete-vm.sh没有返回错误代码,则调用vm_script.sh

如果您不想陷入等待终止headnode.sh的shell,请使用nohup ./headnode.sh &

进行调用