在 nohup 中运行脚本 shell 的一部分

Pap*_*cel 0 linux shell bash

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

#!/bin/bash

command_1
script2.sh
script3.sh
...
(tests & loops, etc)
script4.sh
script5.sh
Run Code Online (Sandbox Code Playgroud)

我想要的是在 nohup 模式下运行从script3.shscript5.sh的部分,而不使用命令“nohup”或“&”,因此如果用户断开连接,脚本继续执行。

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

lar*_*sks 9

的主要目的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.
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用该trap命令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
Run Code Online (Sandbox Code Playgroud)

您可能希望确保脚本的输出被定向到一个文件(否则,即使脚本继续运行,您在断开连接后也会丢失任何输出)。

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