What is the easiest way to "detach/daemonize" a Bash script?

Warpling picture Warpling · Dec 6, 2010 · Viewed 22.9k times · Source

What I am trying to do is write a Bash script that sleeps for a set amount of time before using the mac say command to speak some text.

I'd like to be able to run the command and then close the terminal so it will still speak at the set time. I've looked into nohup, detach, launchd, and putting the process in the background, but all of these solutions still result in the process being terminated once the terminal is closed. Should I somehow make some sort of zombie child process to do this? What is the best solution? Thank you

# Simple Example of main code
sleep 10;
say hello;
exit;

Answer

Jonathan Leffler picture Jonathan Leffler · Dec 6, 2010

Section 3.7.6 of the Bash Manual says:

The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIGCONT to ensure that they receive the SIGHUP. To prevent the shell from sending the SIGHUP signal to a particular job, it should be removed from the jobs table with the disown builtin (see Section 7.2 [Job Control Builtins], page 88) or marked to not receive SIGHUP using disown -h.

So, using either nohup or disown should do the trick. Or you can do:

trap "" 1
sleep 10
say hello

That 'trap' line ignores signal 1, SIGHUP; you can probably also write 'trap "" HUP".