Linux – init script that logs output of the script

daemoninitlinuxlog-fileslogging

How can this be done? I know it's pretty simple and includes appending something like & or &> to the actual command that starts the init script.

But, what is the best approach and how can it be ensured that the init script detaches itself, suppose the log file is /var/log/customDaemon.log ?

Here's the init script I have. I'm also not sure if the approach in the script is neat or just a nasty hack.

#!/bin/bash
#
# /etc/rc.d/init.d/customDaemon
#
# description: "The Daemon"
# processname: customDaemon
# pidfile: "/var/run/customDaemon.pid"

# Source function library.
. /etc/rc.d/init.d/functions

start() {
    echo "Starting customDaemon"
    /var/customDaemon &> /dev/null &
    return 1
}

stop() {
    echo "Stopping tweriod"
    prockill customDaemon   
    return 2
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    reload)
        restart
    ;;
    status)
        status customDaemon
    ;;
    *)
        echo "Usage: customDaemon [start|stop|restart|status]"
        exit 1
    ;;
esac

Best Answer

Try this:

/var/customDaemon >> /var/log/customDaemon.log 2>&1 &

I suggest you should running the service with normal user instead of root.

To show the [ OK ], [ FAILED ] messages, you can check the exit status, something like this:

/var/customDaemon >> /var/log/customDaemon.log 2>&1 &
RETVAL=$?
[ $RETVAL = 0 ] && echo -ne '\t\t\t\t\t[  \033[32mOK\033[0m  ]\n'

You may also take a look at pre-define funtions in /etc/rc.d/init.d/functions: daemon, killproc, action, ...

/var/customDaemon >> /var/log/customDaemon.log 2>&1 &
RETVAL=$?
[ $RETVAL = 0 ] && action $"Starting customDaemon... " /bin/true