运行 一个 shell 脚本并立即将其置于后台,但保留检查其输出的能力

Run a shell script and immediately background it, however keep the ability to inspect its output

我如何运行一个shell脚本并立即背景它,但是通过拖尾[=12保持随时检查其输出的能力=].

如果我能前台进程太晚就好了。


P.S.

如果您还可以告诉我如何将后台进程“发送”到可能已初始化或未初始化的 GNU 屏幕,那就太好了。

启动进程时'background'进程

只需在命令后添加一个符号 (&)。

如果程序写入标准输出,它仍会写入您的控制台/终端。


将进程置于前台

只需使用 fg command. You can see a list of jobs in the background with jobs.

例如:

sh -c 'sleep 3 && echo I just woke up' & jobs


后台运行当前 运行ning 进程

如果您已经在前台启动了进程,但您想将其移动到后台,您可以执行以下:

  1. Ctrl+z 使当前进程进入休眠状态,return 进入你的 shell。此过程将暂停,直到您发送另一个信号。
  2. 运行 bg 命令恢复进程,但在 background 而不是 前景.

另一种方法是在行尾使用 nohup 命令和 &

像这样

nohup whatevercommandyouwant whateverparameters &

这将 运行 它在后台并将其输出发送到 nohup.log 文件。

现代且易于使用的方法允许管理多个进程并具有一个漂亮的终端 UI 是 hapless 实用程序。

安装 pip install hapless(或 python3 -m pip install hapless),仅 运行

$ hap run my-command  # e.g. hap run python my_long_running_script.py
$ hap status  # check all the launched processes
$ hap logs 4  # output logs for you 4th background process
$ hap logs -f 2  # continuously stream logs for the 2nd process

有关详细信息,请参阅 docs