Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I've written quite a few shell scripts over the years (but I'm certainly not a sysadmin) and there's something that always caused me troubles: how can I fork a shell command immune to hangups in the background from a Bash script?

For example if I have this:

command_which_takes_time input > output

How can I "nohup" and fork this?

The following doesn't seem to do what I want:

nohup command_which_takes_time input > output &

What is the syntax I am looking for and what am I not understanding?

share|improve this question

4 Answers 4

up vote 6 down vote accepted

Try creating subshell with (...) :

( command_which_takes_time input > output ) &

Example:

~$ ( (sleep 10; date) > /tmp/q ) &
[1] 19521
~$ cat /tmp/q # ENTER
~$ cat /tmp/q # ENTER
(...) #AFTER 10 seconds
~$ cat /tmp/q #ENTER
Wed Jan 11 01:35:55 CET 2012
[1]+  Done                    ( ( sleep 10; date ) > /tmp/q )
share|improve this answer

This will work (do not type any extra spaces):

command &>output.file
share|improve this answer

Freebsd:

/usr/sbin/daemon -f <command> <command args>
share|improve this answer

You should try setsid(1). Use it like you'd use nohup:

setsid command_which_takes_time input > output

This (as per the setsid(2) manpage), does a fork(2), an _exit(2) of the parent process, then the child process calls setsid(2) to create a new process group (session).

You can't kill that by logging out, and it's not part of the Bash job control shebang. For all intents and purposes, it's a proper daemon.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.