自我守护的bash脚本

pep*_*uan 9 bash daemon

我想让脚本成为自我守护,即不需要nohup $SCRIPT &>/dev/null &在shell提示符下手动调用.

我的计划是创建一段代码,如下所示:

#!/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
Run Code Online (Sandbox Code Playgroud)

这是明智的吗?你有更好的选择吗?

kon*_*box 9

这是我看到的东西.

if [[ $1 != "--daemonize" ]]; then  
Run Code Online (Sandbox Code Playgroud)

不是那样的 == --daemonize?

nohup $SCRIPTNAME --daemonize "${PARAMS[@]}" &>/dev/null &
Run Code Online (Sandbox Code Playgroud)

您可以只召唤放置在后台的子shell,而不是再次调用脚本:

(
    Codes that run in daemon mode.
) </dev/null >/dev/null 2>&1 &
disown
Run Code Online (Sandbox Code Playgroud)

要么

function daemon_mode {
    Codes that run in daemon mode.
}

daemon_mode </dev/null >/dev/null 2>&1 &
disown
Run Code Online (Sandbox Code Playgroud)

  • 在上一版本中不需要括号.由于&,函数将在新的子shell中运行. (2认同)