How to include nohup inside a bash script?

felipebm picture felipebm · May 29, 2011 · Viewed 39k times · Source

I have a large script called mandacalc which I want to always run with the nohup command. If I call it from the command line as:

nohup mandacalc &

everything runs swiftly. But, if I try to include nohup inside my command, so I don't need to type it everytime I execute it, I get an error message.

So far I tried these options:

nohup (
command1
....
commandn
exit 0
)

and also:

nohup bash -c "
command1
....
commandn
exit 0
" # and also with single quotes.

So far I only get error messages complaining about the implementation of the nohup command, or about other quotes used inside the script.

cheers.

Answer

user3850 picture user3850 · May 29, 2011

Try putting this at the beginning of your script:

#!/bin/bash

case "$1" in
    -d|--daemon)
        $0 < /dev/null &> /dev/null & disown
        exit 0
        ;;
    *)
        ;;
esac

# do stuff here

If you now start your script with --daemon as an argument, it will restart itself detached from your current shell.

You can still run your script "in the foreground" by starting it without this option.