简体   繁体   English

如何在脚本退出时未停止的bash脚本中运行命令?

[英]How to run a command in bash script which is not stopped when the script exits?

I have a BASH script which runs other commands and I would like to keep them running in case the main script stops. 我有一个BASH脚本运行其他命令,我想让它们运行,以防主脚本停止。 I tried to run those commands with & but it didn't help. 我尝试用&运行这些命令,但它没有帮助。 Am I doing something wrong? 难道我做错了什么?

This is normal: the shell's job control mechanism terminates its jobs when it exits. 这是正常的:shell的作业控制机制在退出时终止其作业。

There are at least two solutions: 至少有两种解决方案:

  • use disown after you have launched a job; 在你找到工作后使用disown ;
  • use at to schedule your job at a later time; 用于at以后安排你的工作;
  • or use the nohup command. 或使用nohup命令。

Now, there is the question of what you want to do with the output of the command you launch in the background: 现在,问题是您要对在后台启动的命令的输出做什么:

  • with disown , you lose it; 如果被disown ,你就会失去它;
  • with at , stdout and stderr are sent to you by mail (but then you can redirect stdout/stderr if you want); at ,stdout和stderr通过邮件发送给你(但是如果你愿意,你可以重定向stdout / stderr);
  • with nohup , you define the output file yourself. 使用nohup ,您自己定义输出文件。

尝试'nohup'命令运行COMMAND ,忽略挂断信号

nohup COMMAND &

Try using nohup (stands for no hangup) before your command: 在命令之前尝试使用nohup(代表没有挂起):

nohup <your command>

It will forward the stdout of the command into a file called nohup.out by default. 默认情况下,它会将命令的stdout转发到名为nohup.out的文件中。

以下是如何执行此操作的示例:

nohup your_command < /dev/null > output.log 2>&1 &

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM