nohup(no hang-up)命令在 Linux 中用于在后台运行程序,即使关闭终端或断开连接,程序也会继续运行
基本用法:
nohup command &
这里,command 是你想要在后台运行的命令。& 符号将命令放入后台运行。
将输出重定向到文件:
nohup command > output.log 2>&1 &
这里,我们将标准输出(stdout)和标准错误(stderr)都重定向到名为 output.log 的文件。这样,你可以随时查看程序的输出,即使关闭终端也不会丢失。
使用 ; 结合多个命令:
nohup command1 ; command2 &
这里,command1 和 command2 将按顺序在后台运行。如果 command1 成功执行,command2 也会在后台运行。
使用 && 结合多个命令:
nohup command1 && command2 &
这里,只有当 command1 成功执行后,command2 才会在后台运行。
使用 || 结合多个命令:
nohup command1 || command2 &
这里,如果 command1 执行失败,command2 将在后台运行。
使用 ;、&& 和 || 结合多个命令:
nohup command1 ; command2 && command3 || command4 &
这里,command1 将首先在后台运行。无论 command1 的执行结果如何,command2 都会在后台运行。如果 command2 成功执行,command3 将在后台运行;否则,command4 将在后台运行。
请注意,使用 nohup 命令时,最好将输出重定向到文件,以防止输出丢失。同时,为了避免意外关闭终端导致程序中断,可以使用 disown 命令将进程从当前 shell 的作业表中移除。