Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exiting shell script with background processes

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.

I've tried to run commands via

nohup myInScript.sh &

also I've tried to use at the end of 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.

like image 767
uniquepito Avatar asked Nov 14 '11 14:11

uniquepito


2 Answers

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.

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.

like image 189
Sodved Avatar answered Oct 14 '22 10:10

Sodved


The solution above works most of the time:

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

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

at now -f my_script.sh

like image 35
Amir Mehler Avatar answered Oct 14 '22 10:10

Amir Mehler