在nohup中运行一部分脚本shell

如何在nohup模式下运行shell脚本的一部分? 我的脚本是这样的:

#!/bin/bash command_1 script2.sh script3.sh ... (tests & loops, etc) script4.sh script5.sh 

我想在没有使用'nohup'或'&'命令的情况下以nohup模式从script3.shscript5.sh运行,所以如果用户断开连接,脚本将继续执行。

不知道我的问题是否足够清楚:)谢谢!

nohup的主要目的是将程序与HUP信号隔离,通常在控制TTY被断开(例如,由于用户注销)时被接收。

你可以使用shell内置的命令trap完成同样的事情:

 $ help trap Trap signals and other events. Defines and activates handlers to be run when the shell receives signals or other conditions. ARG is a command to be read and executed when the shell receives the signal(s) SIGNAL_SPEC. If ARG is absent (and a single SIGNAL_SPEC is supplied) or `-', each specified signal is reset to its original value. If ARG is the null string each SIGNAL_SPEC is ignored by the shell and by the commands it invokes. 

因此,您可以使用trap命令通过传递空string作为操作来隔离HUP信号的部分脚本。 例如:

 #!/bin/sh command_1 script2.sh # Starting ignoring HUP signal trap "" HUP script3.sh ... (tests & loops, etc) script4.sh # Resume normal HUP handling. trap - HUP script5.sh 

您可能需要确保输出到您的脚本被引导到一个文件(否则即使脚本继续运行,您将断开连接后,将丢失任何输出)。

您可能还想考虑在屏幕的控制下简单地运行脚本,因为这样做的好处是您可以在断开连接后重新连接到正在运行的脚本。

一般来说,当脚本仍然在后台运行时退出脚本是不好的做法。

应用KISS原则,或“保持简单,萨姆”(Sam的各种价值观)。 你明白没有,只是用它。

如果您希望script3.sh通过script5.sh以及其中的所有条件和循环在脚本返回到shell提示后运行完成,请将该脚本的该部分放在单独的文件中。

你现在得到两个脚本。 首先是脚本script0.sh

 #!/bin/bash command_1 script2.sh nohup script35.sh & exit 

script35.sh:

 #! /bin/bash script3.sh ... (tests & loops, etc) script4.sh script5.sh 

如果你想从cron启动脚本, 为什么要麻烦 ? 如果从shell会话开始,请遵循@larsks的build议,并使用terminal仿真器/多路复用器(如screentmux