pepoluan
pepoluan

Reputation: 6780

Self-daemonizing bash script

I want to make a script to be self-daemonizing, i.e., no need to invoke nohup $SCRIPT &>/dev/null & manually on the shell prompt.

My plan is to create a section of code like the following:

#!/bin/bash
SCRIPTNAME="$0"

...

# Preps are done above
if [[ "$1" != "--daemonize" ]]; then
    nohup "$SCRIPTNAME" --daemonize "${PARAMS[@]}" &>/dev/null &
    exit $?
fi

# Rest of the code are the actual procedures of the daemon

Is this wise? Do you have better alternatives?

Upvotes: 11

Views: 8003

Answers (1)

konsolebox
konsolebox

Reputation: 75458

Here are things I see.

if [[ $1 != "--daemonize" ]]; then  

Shouln't that be == --daemonize?

nohup $SCRIPTNAME --daemonize "${PARAMS[@]}" &>/dev/null &

Instead of calling your script again, you could just summon a subshell that's placed in a background:

(
    Codes that run in daemon mode.
) </dev/null >/dev/null 2>&1 &
disown

Or

function daemon_mode {
    Codes that run in daemon mode.
}

daemon_mode </dev/null >/dev/null 2>&1 &
disown

Upvotes: 11

Related Questions