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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44222883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:32:27  来源:igfitidea点击:

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

bashbackground-processdaemongnu-screenjob-control

提问by american-ninja-warrior

How can I run a shell script and immediately background it, however keep the ability to inspect its output any time by tailing /tmp/output.txt

我怎样才能运行一个 shell 脚本并立即将它作为后台运行,但是通过拖尾 /tmp/output.txt 保持随时检查其输出的能力

It would be nice if I can foreground the process too later.

如果我可以太晚地将过程置于前台,那就太好了。

PS It would be really cool if you can also show me how to "send" the backgrounded process in to a gnu screen that may or may not have been initialized.

PS 如果您还可以向我展示如何将后台进程“发送”到可能已初始化或未初始化的 gnu 屏幕,那将非常酷。

回答by Jon Wolski

To 'background' a process when you start it

在启动进程时“背景”它

Simply add an ampersand (&) after the command.

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

If the program writes to standard out, it will still write to your console/terminal.

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

To foreground the process, simply use the fgcommand.

要将进程置于前台,只需使用该fg命令。

(You can see a list of jobs in the background with jobs.)

(您可以在后台查看工作列表jobs。)

for example:

例如:

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

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

To background a currently running process

将当前正在运行的进程设为后台

If you have already started the process in the foreground, but you want to move it to the background, you can do the following:

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

  1. Press Ctrl+z to put the current process to sleep and return to your shell. (This process will be paused until you send it another signal.)
  2. Run the bgcommand to resume the process, but have it run in the background instead of the foreground.
  1. 按 Ctrl+z 使当前进程进入睡眠状态并返回到您的 shell。(此过程将暂停,直到您向其发送另一个信号。)
  2. 运行bg命令以恢复进程,但让它在后台而不是前台运行。

回答by israelss

Another way is using the nohupcommand with &at the end of the line.

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

Something like this

像这样的东西

nohup whatevercommandyouwant whateverparameters &

This will run it in the background and send its output to a nohup.log file.

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