Bash – How to totally fork a shell command that is using redirection

bashforknohupscripting

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?

Best Answer

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 )
Related Question