8

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.

uniquepito
  • 833
  • 2
  • 9
  • 17

2 Answers2

13

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.

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
Sodved
  • 8,428
  • 2
  • 31
  • 43
  • what if I don't want the some.log? seems exactly my problem, because (and I forgot to mention) I'm running scripts remotely vie ssh – uniquepito Nov 14 '11 at 15:05
  • 1
    just use `/dev/null` for that too. Basically you just need to redirect it somewhere in order to detach it from the terminal. Actually you may find that nohup automatically redirects stdout and stderr to nohup.out, so all you may need is the stdin redirection. – Sodved Nov 14 '11 at 15:06
  • one question yet. what if I want to redirect all messages to screen? – uniquepito Nov 14 '11 at 16:15
  • 1
    You can't have your cake and eat it too :) The parent process effectively "owns" the connection to the terminal, which is connected to your screen via `ssh`. This is exactly why the system was not letting it exit properly before. Think about it. When your `ssh` exits and returns you, there is no longer a connection between the remote and local machines, so there is no way for the child process (running on the `remote` machine) to write a message to your screen (which is now showing the `local` machine). – Sodved Nov 14 '11 at 16:43
4

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

Amir Mehler
  • 4,140
  • 3
  • 27
  • 36