bash 使用后台进程退出 shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8122780/
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-18 01:03:48  来源:igfitidea点击:

exiting shell script with background processes

bashshellbackground-process

提问by uniquepito

I need somehow to exit my script.sh (with return code - would be the best) which runs some other commands and other scripts in the background.

我需要以某种方式退出在后台运行一些其他命令和其他脚本的 script.sh(带有返回码 - 将是最好的)。

I've tried to run commands via

我试图通过运行命令

nohup myInScript.sh &

also I've tried to use at the end of script.sh

我也尝试在 script.sh 的末尾使用

disown -a[r]

and also I've tried to kill it

而且我也试图杀死它

kill $$ 

but the script just hangs after last command and won't quit. How to force it to exit after running its commands? please help.

但是脚本只是在最后一个命令之后挂起并且不会退出。运行命令后如何强制它退出?请帮忙。

edit: To be more specific, I'm running the script remotely via ssh on the other machine.

编辑:更具体地说,我在另一台机器上通过 ssh 远程运行脚本。

回答by Sodved

From memory a login shell will be kept around even when it finishes if any of its still running children have standard (terminal) file handles open. Normal (sub process) shells do not seem to suffer from this. So see if changing your nohup line to the following makes any difference.

从内存中,如果任何仍在运行的子进程打开了标准(终端)文件句柄,即使登录 shell 完成,它也将保留在内存中。正常(子进程)shell 似乎不受此影响。因此,看看将您的 nohup 行更改为以下内容是否有任何区别。

nohup myInScript.sh >some.log 2>&1 </dev/null &

On Centos5 I do not get the problem if I run parent.sh. But I do if I run ssh localhost parent.sh. In this case the I/O redirection I showed above solves the problem.

在 Centos5 上,如果我运行parent.sh. 但如果我跑,我会这样做ssh localhost parent.sh。在这种情况下,我上面展示的 I/O 重定向解决了这个问题。

回答by Amir Mehler

The solution above works most of the time:

上面的解决方案大部分时间都有效:

nohup myInScript.sh >some.log 2>&1 </dev/null &

nohup myInScript.sh >some.log 2>&1 </dev/null &

But I've had a case where it didn't, not sure why. Anyway the atcommand did the trick and even looks more classy:

但是我遇到过没有的情况,不知道为什么。无论如何at命令做到了这一点,甚至看起来更优雅:

at now -f my_script.sh

at now -f my_script.sh