Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 595
Warpling Avatar asked Dec 06 '10 18:12

Warpling


People also ask

How do I detach a process in bash?

Here is how you can detach a process from bash shell. If a given process is running in the foreground, press Ctrl+z to interrupt it. Then run it in the background. Finally, type disown along with job sequence number of the backgrounded job.

How do I get out of bash shell in terminal?

To exit from bash type exit and press ENTER . If your shell prompt is > you may have typed ' or " , to specify a string, as part of a shell command but have not typed another ' or " to close the string. To interrupt the current command press CTRL-C .

Can a bash script remove itself?

Only when the last program closes its handle does the file really get deleted. So, in a sense, yes, a shell script can delete itself, but it won't really be deleted until after the execution of that script finishes.

What are the ways to get out of a bash loop inside of a script without exiting the actual script?

If you want to exit the loop instead of exiting the script, use a break command instead of an exit. #!/bin/bash while true do if [ `date +%H` -ge 17 ]; then break # exit loop fi echo keep running ~/bin/process_data done …


1 Answers

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".

like image 133
Jonathan Leffler Avatar answered Sep 30 '22 17:09

Jonathan Leffler